C++ solution


  • 0

    Here is my cpp solution.

    class Solution {
    public:
        string addBinary(string a, string b) {
            string res;
            int i = (int) a.size() - 1;
            int j = (int) b.size() - 1;
            int carry = 0;
            do {
                int ai = i >= 0 ? a[i--] - '0' : 0;
                int bj = j >= 0 ? b[j--] - '0' : 0;
                int sum = ai + bj + carry;
                res.push_back((sum & 1) + '0');
                carry = sum >> 1;
            } while (i >= 0 || j >= 0 || carry > 0);
            reverse(res.begin(), res.end());
            return res;
        }
    };
    

Log in to reply
 

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