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 MaxLen = (a.length()>b.length())?(a.length() + 1):(b.length() + 1);
        string ret(MaxLen,'0');string copya(MaxLen,'0');string copyb(MaxLen,'0');
        int cursor = a.length()-1;
        int cursorret = MaxLen - 1;
        while(cursor >= 0)
        {copya[cursorret] = a[cursor];cursor--;cursorret--;}

        cursor = b.length()-1;cursorret = MaxLen - 1;
        while(cursor >= 0)
        {copyb[cursorret] = b[cursor];cursor--;cursorret--;}

        int p = MaxLen - 1;
        int sign = 0;
        while(p >= 0)
        {
            int tempa = copya[p] - 48;
            int tempb = copyb[p] - 48;
            int sum = tempa + tempb + sign;
            if(sum == 0) 
            {ret[p] = '0'; sign = 0;}
             else if(sum == 1)
            {ret[p] = '1';sign = 0;}
             else if(sum == 2)
            {ret[p] = '0';sign = 1;}
             else if(sum == 3)
            {ret[p] = '1';sign = 1;}
             p--;
        }

        if(ret[0] == '0')
        {ret.erase(0,1);}
        return ret;
    }
};

 

posted on 2014-05-28 12:15  berkeleysong  阅读(140)  评论(0编辑  收藏  举报

导航