Easy understanding C++ code (3ms)


  • 0
    P
        string addBinary(string a, string b) {
            int carry = 0;
            int ta = a.size() - 1, tb = b.size() - 1;
            string out = "";
            while (ta >= 0|| tb >= 0 ) {
                int sum = 0;
                if (ta >= 0) sum += a[ta--]-'0';
                if (tb >= 0) sum += b[tb--]-'0';
                sum += carry;
                carry = sum / 2;
                sum = sum % 2;
                out = to_string(sum) + out ;
            }
            if (carry) out = to_string(carry) + out;
            return out;
        }
    

Log in to reply
 

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