4ms 12-lines O(1)-Space C++ Solution


  • 0

    The idea is to add the two binary numbers (represented as strings) from back to forth bit by bit and store the result in the longer string. After the shorter string has been added, we continue to handle the carry bit. We may need to append the carry bit to the beginning of the longer string if necessary.

    The code is as follows.

    class Solution {
    public:
        string addBinary(string a, string b) {
            int m = a.length(), n = b.length(), c = 0, i, j;
            if (m < n) return addBinary(b, a);
            for (i = m - 1, j = n - 1; j >= 0; i--, j--) {
                int ad = a[i] - '0', bd = b[j] - '0';
                a[i] = (ad ^ bd ^ c) + '0';
                c = (ad + bd + c >= 2);
            }
            for (; i >= 0; i--) {
                int ad = a[i] - '0';
                a[i] = (ad ^ c) + '0';
                c = (ad + c >= 2);
            }
            if (c) a = '1' + a;
            return a; 
        }
    };
    

    Running the above code on the simple example a = "1", b = "11" will help you get all its details (both the two for loops and the two if statements will be hit) :-)


Log in to reply
 

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