Add Binary

2017/11/22 posted in  leetcode

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 fw = 0;
        string result = "";
        for(int i = a.size()-1,j=b.size()-1;i>=0||j>=0;i--,j--){
            int ag = i>=0?a[i]-'0':0;
            int bg = j>=0?b[j]-'0':0;
            int tmp = (ag+bg+fw)%2;
            fw = (ag+bg+fw)/2;
            
            result = char(tmp+'0')+result;
        }
        if(fw==1){
            result = '1'+result;
        }
        
        return result;
    }
};