A clear C++ approach. 6ms.


  • 0
    Y
    class Solution {
    public:
        string addBinary(string a, string b) {
        	stringstream ss;int i,t,p,tmp=0;
            string maxs=(a.size()>=b.size())?a:b;
            string mins=(a.size()<b.size())?a:b;
            for(i=mins.size()-1;i>=0;i--){
            	t=p=0;
            	ss<<maxs[maxs.size()-mins.size()+i];ss>>t;ss.clear();
            	ss<<mins[i];ss>>p;ss.clear();
            	if(t+p+tmp>1){
            		if(t+p+tmp==3) {tmp=1;mins[i]='1';}
            		else {tmp=1;mins[i]='0';}
            	}
            	else if(t+p+tmp==1){tmp=0;mins[i]='1';}
            	else{tmp=0;mins[i]='0';}
            }
            maxs=maxs.substr(0,maxs.size()-mins.size())+mins;
            if(mins.size()<maxs.size()){
            	if(!tmp) return maxs;
            	for(int j=maxs.size()-mins.size()-1;j>=0;j--){
            		t=0;ss<<maxs[j];ss>>t;ss.clear();
            		if(t+tmp>1){tmp=1;maxs[j]='0';}
            		else {tmp=0;maxs[j]='1';break;}
            	}
            	if(tmp) maxs='1'+maxs;
            }
            else{if(tmp) maxs='1'+maxs;}
            return maxs;
        }
    };

Log in to reply
 

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