二进制相加

本来是打算直接用 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;
}

 

posted @ 2015-09-05 15:41  wu_overflow  阅读(611)  评论(0编辑  收藏  举报