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;
    }
  • 相关阅读:
    smm框架整合实现登录功能
    Java线程面试题
    JAVA面试题
    Linux基础命令
    Java面试题技术类
    Spring+Spring MVC+MyBatis框架集成
    C语言 编程练习22题
    C语言 基础练习40题
    Python3-socket网络知识储备
    python3-面向对象进阶(内置方法)
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4783321.html
Copyright © 2011-2022 走看看