67. 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) {
        if (a == "" && b == "") return "";
        
        string result = "";
        int c = 0, i = a.length()-1, j = b.length()-1;
        while (i >= 0 || j >= 0) {
            
            c += i < a.length() ? (a[i] - '0') : 0;
            c += j < b.length() ? (b[j] - '0') : 0;
            
            result = char(c%2 + '0') + result;
            c /= 2;
            --i, --j;
        }
        
        return c ? char(c+'0') + result : result;
    }
};
原文地址:https://www.cnblogs.com/linjj/p/5261257.html