C++ solution,3ms


  • 0
    W
    class Solution {
    public:
        string addBinary(string a, string b) {
            string ret = "";
            int carry = 0, alen = a.length(), blen = b.length();
            for (int i = 1; i <= fmax(alen, blen); i++) {
                int atmp = (alen - i) < 0 ? 0 : a[alen - i] - '0';
                int btmp = (blen - i) < 0 ? 0 : b[blen - i] - '0';
                ret.insert(0, 1, (atmp + btmp + carry) % 2 + '0');
                carry = (atmp + btmp + carry) / 2;
            }
            if (carry != 0) ret.insert(0, 1, '1');
            return ret;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.