No arithmetic operations on the input, Just comparisons...


  • 0
    A

    Actually there is no need to do any char subtractions or value additions, or fancy or xor bit ops etc. :)
    It's all either '1's or '0's. So just based on char comparisons, here is my 3ms c++ solution:

        string addBinary(string a, string b) 
        {
            int i = a.length() - 1;
            int j = b.length() - 1;
            
            string result = i > j ? a : b;
            int k = result.length() -1;
    
            char first, second, sum;
            bool carry = false;
            while (i >= 0 || j >= 0)
            {
                first = i >= 0 ? a[i--] : '0';
                second = j >= 0 ? b[j--] : '0';
                
                bool eq = first == second;
                sum = eq ^ carry ? '0' : '1';
                if(eq) carry = first == '1' ;
                
                result[k--] = sum;
            }
            
            if(carry) result = '1'  + result;    
            
            return result;
        }
    

Log in to reply
 

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