C++ 6ms simple solution with prefix 0


  • 0
    A
    class Solution {
    public:
        string addBinary(string a, string b) {
            int len = MakeLengthEqual(a, b);
            
            int carryOver = 0;
            string ans(len, '1');
            
            for (int i = len - 1; i >= 0; i--) {
                int cur = int(a[i] + b[i] - '0' * 2) + carryOver;
                carryOver = cur / 2;
                ans[i] = char(cur % 2 + '0');
            }
            
            if (carryOver) {
                ans = '1' + ans;
            }
            
            return ans;
        }
        
        int MakeLengthEqual(string &a, string &b) {
            if (a.size() >= b.size()) {
                lengthen(b, a.size() - b.size());
                return a.size();
            }
            else {
                lengthen(a, b.size() - a.size());
                return b.size();
            }
        }
        
        void lengthen(string &s, int addSize) {
            string preZero = "";
            for (int i = 0; i < addSize; i++) {
                preZero += "0";
            }
            
            s = preZero + s;
        }
    };

Log in to reply
 

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