Leetcode Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

     两个二进制相加,由于低位在右,先把两个字符串翻转,这样从左向右依次按位相加,声明carry变量为进位量,确保a的长度不小于b的长度,把b加到a上,最后翻转过来。

class Solution {
public:
    string addBinary(string a, string b) {
        if(a.length()==0)return b;
        if(b.length()==0)return a;
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        if(a.length()<b.length()){
            string s=a;
            a=b;
            b=s;
        }
        int ai=0,bi=0,carry=0;
        while(ai<a.length()&&bi<b.length()){
            int num=a[ai]-'0'+(b[bi]-'0')+carry;
            carry=num/2;
            num=num%2;
            a[ai]=num+'0';
            ai++;bi++;
        }
        while(ai<a.length()){
            if(carry==0){reverse(a.begin(),a.end());return a;}
            int num=a[ai]-'0'+carry;
            carry=num/2;
            num=num%2;
            a[ai]=num+'0';
            ai++;
        }
        if(carry==1)a+="1";
        reverse(a.begin(),a.end());
        return a;
    }
};


你可能感兴趣的:(LeetCode)