A relatively short c++ solution


  • 0
    J
    class Solution {
    public:
    string addBinary(string a, string b) {
         string *p;
         if(a.size()<b.size()) p=&b;
         else p=&a; 
         int i=a.size()-1,j=b.size()-1, k=max(i,j), c=0;
         while(i>=0 and j>=0) { 
                int m=a[i]+b[j]+c-'0'-'0'; 
                (*p)[k]=m%2+'0'; 
                c=m/2;
                i--;j--;k--;
         }
         while(k>=0){
             int m=(*p)[k]+c-'0'; 
             (*p)[k]='0'+m%2; 
             c=m/2;
             k--; 
         }
         if(c>0) (*p)="1"+(*p);
         
    
         return *p;
    }
    };

Log in to reply
 

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