4m C++ solution, direct string + string, with comments


  • 0
    D
    class Solution {
    public:
    string addBinary( string a,  string b) {
        string ret="";
        int sig=0;
        int i;
        /* lpad shorter string with 0*/
        int maxlen=(a.size()>b.size()?a.size():b.size());
        int lenGap=abs((int)a.size()-(int)b.size()); 
    
        if(a.size()>b.size())
            for(i=0;i<lenGap;i++)
                b='0'+b;
        else
            for(i=0;i<lenGap;i++)
                a='0'+a;
        
        for(i=maxlen-1;i>=0;i--)
                {
               ret=(char)(((a[i]-'0')^(b[i]-'0')^sig)+48)+ret; 
                ((a[i]-'0')+(b[i]-'0')+sig)>=2?sig=1:sig=0;
                }
                
        if(sig==1)
            ret='1'+ret;
            
        return ret;
    }
    

    };


Log in to reply
 

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