A simple trick of adding "0" before the string with shorter length. C++ Solution.


  • 0
    G
    class Solution {
    public:
        string addBinary(string a, string b) {
            string addResult="";
            int maxLength = max(a.length(),b.length());
            while (a.length()<maxLength) {
                a="0"+a;
            }
            while (b.length()<maxLength) {
                b="0"+b;
            }
            int ii=maxLength-1;
            int next = 0;
            while (ii>=0) {
                int num1 = a[ii]-'0';
                int num2 = b[ii]-'0';
                int num =(num1+num2+next)%2;
                if (num1+num2+next>=2)
                    next = 1;
                else
                    next = 0;
                addResult = to_string(num) +addResult;
                ii=ii-1;
            }
            if (next == 1)
                addResult ="1"+addResult;
            return addResult;
            
        }
    };

Log in to reply
 

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