zoukankan      html  css  js  c++  java
  • 二进制相加

    本来是打算直接用 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;
    }
  • 相关阅读:
    SQL随记(四)
    一些有用的方法命令
    导航目录
    HTML中       等6种空白空格的区别
    MyBatis学习资料
    Spring Cloud资料
    聚类算法对比
    Spark 读取HBase数据
    ZooKeeper设置ACL权限控制
    大数据工具选择
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4783321.html
Copyright © 2011-2022 走看看