4ms clean cpp solution


  • 0
    Z
    class Solution {
    public:
    string addBinary(string a, string b) {
        int alength = a.length();
    	int blength = b.length();
    	int addBit = 0;
    	int i = alength-1, j=blength-1;
    	string str,result;
    	
    	while(i>=0||j>=0){
    			str += ((i>=0?a[i]:'0')+(j>=0?b[j]:'0')+addBit-2*'0')%2+'0';
    			addBit = ((i>=0?a[i]:'0')+(j>=0?b[j]:'0')+addBit-2*'0')/2;
    			i--;j--;
    	}
    	if(addBit)
    		str+='1';
    	
    	for(int p = str.length()-1;p>=0;p--){
    		result+=str[p];
    	}
    	
    	return result;
    }
    };

Log in to reply
 

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