首页 > 代码库 > LeetCode--Add Binary

LeetCode--Add Binary

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

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

class Solution 
{
public:
    string addBinary(string a, string b) 
    {
        int m = a.length();
        int n = b.length();
        if(m == 0)
            return b;
        if(n == 0)
            return a;
        if(n>m)
            return addBinary(b,a);
        n--;
        m--;
        string res="";
        int count = 0;
        while(n>=0 && m>=0)
        {
            int a_int = a[m]-48;
            int b_int = b[n]-48;
            int cal = count+a_int+b_int;
            count = cal/2;
            cal = cal%2;
            res += (char)(cal+48);
            m--;
            n--;
        }
        while(m>=0)
        {
            int a_int = a[m]-48;
            int cal = count+a_int;
            count = cal/2;
            cal = cal%2;
            res += (char)(cal+48);
            m--;
        }
        while(count>0)
        {
            res += (char)(count%2 + 48);
            count = count/2;
        }
        n = res.length()-1;
        int i=0;
        while(i<n)
        {
            char t = res[i];
            res[i] = res[n];
            res[n] = t;
            i++;
            n--;
        }
        return res;
    }
};


LeetCode--Add Binary