c++ solution (O(max(n, m)))


  • 0
    string addBinary(string a, string b) {
        string res;
        int cur = 0;
        for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0 || cur > 0; --i, --j) {
            cur += ((i >= 0) ? a[i] - '0' : 0) + ((j >= 0) ? b[j] - '0' : 0);
            res = (char)(cur % 2 + '0') + res;
            cur /= 2;
        }
        return res;
    }
    

Log in to reply
 

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