C++ solution [4ms] [15lines]


  • 0
    W
    string addBinary(string a, string b) {
        string res(max(a.size(),b.size())+1,'0');
        int i = a.size() - 1, j = b.size() - 1, cur = res.size();
        while(i >= 0 && j >= 0) res[--cur] = a[i--] + b[j--] - '0';
        while(i >= 0) res[--cur] = a[i--];
        while(j >= 0) res[--cur] = b[j--];
        int carry = 0;
        for(i = res.size() - 1;i >= 0; --i){
            int sum = res[i] - '0' + carry;
            carry = sum >> 1;
            res[i] = '0' + sum - (carry << 1);
        }
        if(res[0] == '0') res.erase(0,1);
        return res;
    }

Log in to reply
 

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