【LeetCode】67. Add Binary

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 sizea = a.size();
        int sizeb = b.size();
        if(sizea < sizeb)
            return addBinary(b, a);
        //sizea >= sizeb
        string zeros(sizea-sizeb, '0');
        b = zeros + b;
        int carry = 0;
        for(int i = sizea-1; i >= 0; i --)
        {
            int sum = (a[i]-'0') + (b[i] - '0') + carry;
            if(sum == 0)
                ;
            else if(sum == 1)
            {
                a[i] = '1';
                carry = 0;
            }
            else if(sum == 2)
            {
                a[i] = '0';
                carry = 1;
            }
            else
            {//sum == 3 (1+1+1)
                a[i] = '1';
                carry = 1;
            }
        }
        if(carry == 1)
            a = "1" + a;
        return a;
    }
};

posted @ 2014-12-10 11:29  陆草纯  阅读(2312)  评论(0编辑  收藏  举报