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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string ans;
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        
        int c = 0, i = 0, j = 0, k = 0,s;
        while(i < a.size() || j < b.size()){
            if (i < a.size() && j < b.size()){
                s = c + a[i++] - '0' + b[j++] - '0';
            }else if (i < a.size()){
                s = c + a[i++] - '0';
            }else{
                s = c + b[j++] - '0';
            }
            if (s == 0 || s == 2){
                ans += '0';
            }else {
                ans += '1';
            }
            if (s >= 2){
                c = 1;
            }else{
                c = 0;
            }
        }
        if (c){
            ans += '1';
        }
        
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

 

posted @ 2013-07-13 08:54  一只会思考的猪  阅读(161)  评论(0编辑  收藏  举报