My C++ solution O(n) time where n is the length of the longer number and O(1) space


  • 0
    M

    class Solution {
    public:
    string addBinary(string a, string b) {

        int i=a.length()-1;
        int j=b.length()-1;
        
        int c=0;
        int s=0;
        
        string res="";
        
        while(i>=0 && j>=0)
        {
            s = (a[i]-'0')+(b[j]-'0')+c;
            
            if(s>=2)
            {
                s = s%2;
                c = 1;
            }
            else
            {
                c = 0;
            }
            
            res = to_string(s) + res;
            i--;
            j--;
        }
        
        while(i>=0)
        {
            s = (a[i]-'0')+c;
            
            if(s>=2)
            {
                s = s%2;
                c = 1;
            }
            else
            {
                c = 0;
            }
            
            res = to_string(s) + res;
            i--;
        }
        
        while(j>=0)
        {
            s = (b[j]-'0')+c;
            
            if(s>=2)
            {
                s = s%2;
                c = 1;
            }
            else
            {
                c = 0;
            }
            
            res = to_string(s) + res;
            j--;
        }
        
        if(c==1)
            res = to_string(c) + res;
    
        return res;    
        
    }
    

    };


Log in to reply
 

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