AC, C++, simplify problem by aligning a and b


  • 0
    F
    class Solution {
    public:
        string addBinary(string a, string b) {
            if (a.length() < b.length()) {
                a = string(b.length() - a.length(), '0') + a;
            }
            if (b.length() < a.length()) {
                b = string(a.length() - b.length(), '0') + b;
            }
            
            int carry = 0;
            for (int i = a.length() - 1; i >= 0; i--) {
                carry += (a[i] - '0') + (b[i] - '0');
                a[i] = carry % 2 ? '1' : '0';
                carry /= 2;
            }
            
            return carry == 1 ? "1" + a : a;
        }
    };

Log in to reply
 

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