首页 > 其他 > 详细

二进制相加

时间:2015-09-05 16:21:43      阅读:266      评论:0      收藏:0      [点我收藏+]

本来是打算直接用 bitset 解决问题的,转成二进制再转成十进制,相加后再通过逆运算求得最终的字符串。

然而却存在一个问题,就是溢出,当给出的二进制过于大的时候,相加就解决不了了,因此就要按照字符串来处理。

以下是我的解决方案,虽说很丑,然而速度还行吧:

string addBinary(string a, string b) {
    string result;
    char carry        = 0;
    string* shortStrp = &a;
    string* longStrp  = &b;
    
    if (a.length() > b.length()){
        shortStrp = &b;
        longStrp  = &a;
    }
    
    auto pushFront = [&](const char* s)
    {
        result.insert(0, s);
    };
    
    auto longStrIt  = longStrp->crbegin();
    auto shortStrIt = shortStrp->crbegin();
    
    while (longStrIt != longStrp->crend()){
        if (shortStrIt == shortStrp->crend()){
            auto const sum = (*longStrIt + carry);
            if (sum == 0 + 0){
                pushFront("0");
                carry = 0;
            }
            else if (sum == 0 + 1){
                pushFront("1");
                carry = 0;
            }
            else if (sum == 1 + 1){
                pushFront("0");
                carry = 1;
            }
            ++longStrIt;
        }
        else{
            auto const sum = (*longStrIt + *shortStrIt + carry);
            if (sum == 0 + 0 + 0){
                pushFront("0");
                carry = 0;
            }
            else if (sum == 0 +0 + 1){
                pushFront("1");
                carry = 0;
            }
            else if (sum == 1 + 1 + 0){
                pushFront("0");
                carry = 1;
            }
            else if (sum == 1 + 1 + 1){
                pushFront("1");
                carry = 1;
            }
            ++longStrIt;
            ++shortStrIt;
        }
    }
    if (carry == 1){
        pushFront("1");
    }
    return result;
}

 

二进制相加

原文:http://www.cnblogs.com/wuOverflow/p/4783321.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!