C++ Solution with Binary Addition


  • 0
    M
    #include <algorithm>
    #include <cstdlib>
    
    class Solution {
    public:
        string addBinary(string a, string b) {
            if (a.size() < b.size()) a.insert(0, b.size() - a.size(), '0');
            if (b.size() < a.size()) b.insert(0, a.size() - b.size(), '0');
            string result(a.size(), '0');
            int carry = 0;
            for (int i = a.size() - 1; i >= 0; --i) {
                int sum = a[i] - '0' + b[i] - '0' + carry;
                carry = 0;
                if (sum >= 2) {
                    carry = 1;
                    sum -= 2;
                }
                result[i] = '0' + sum;
            }
            if (carry > 0) result.insert(0, 1, '1');
            return result;
        }
    };
    

  • 0
    A
    This post is deleted!

Log in to reply
 

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