• 二进制相加


    本来是打算直接用 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;
    }
  • 相关阅读:
    100以内质数的算法
    WebAPI和WebService的区别
    .net core 2.0 数据访问-迁移
    .net core 2.0 Redis的基本使用
    .net core 2.0 Autofac
    net core 2.0 + Autofac的坑
    MVC路由机制
    MVC原理
    CentOS安装GIt、上传项目到git仓库
    ARM 汇编指令集 特点5:ARM 多级指令流水线
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4783321.html
Copyright © 2020-2023  润新知