zoukankan      html  css  js  c++  java
  • Leetcode67 二进制求和

    题目:Given two binary strings, return their sum (also a binary string).
    For example,
    a = "11"
    b = "1"
    Return "100".

    思路:二进制加法和普通加法的思路没什么差别,甚至更简单。所需要注意的细节就是进位。从最低位开始,进位可能伴随计算直到最高位。所以每一位的加法运算都要将上一次的进位加进去。

    对于某一位a和b,上一为的进位c,该为求和之后的和是(a+b+c)%2,进位是(a+b+c)/2

    class Solution {
    public:
        string addBinary(string a, string b) {
            if(a.size()==0||a=="0") return b;
            if(b.size()==0||b=="0") return a;
            int lena=a.size()-1,lenb=b.size()-1,increase=0;
            string sum="";
            while(lena>=0 && lenb>=0)
            {
                sum=std::to_string((a[lena]-'0' + b[lenb] - '0' + increase)%2) + sum;
                increase=(a[lena]-'0' + b[lenb] - '0' + increase)/2;
                lena--;
                lenb--;
            }
            while(lena>=0)
            {
                sum=std::to_string((increase+a[lena]-'0')%2)+sum;
                increase=(a[lena]-'0'+increase)/2;
                lena--;
            }
            while(lenb>=0)
            {
                sum=std::to_string((increase+b[lenb]-'0')%2)+sum;
                increase=(b[lenb]-'0'+increase)/2;
                lenb--;
            }
           if(increase==1)
                sum="1"+sum;
            return sum;
        }
    };
    

      

  • 相关阅读:
    别了,DjVu!
    DjVu转PDF
    我的电子书历程
    连续翻页浏览器面临的共同问题
    对超过2TB的硬盘进行分区需要使用parted
    DB2常用命令
    CentOS增加网卡
    mysql相关参数解读
    max_user_connections参数设置试验
    mysql最大连接数试验
  • 原文地址:https://www.cnblogs.com/renzmin/p/11803543.html
Copyright © 2011-2022 走看看