C++ Simple Solution 3ms


  • 0
    S
    class Solution{
    public:
    	string addBinary(string a, string b){
    		int len = max(a.size(), b.size());
    		if(len - a.size() > 0)
    			a.insert(a.begin(), len-a.size(), '0');
    		if(len - b.size() > 0)
    			b.insert(b.begin(), len-b.size(), '0');
    		
    		string c;	
    		int carry = 0;
    		for(int i = len - 1; i >= 0; i --){
    			int t = a[i] - '0' + b[i] -'0' + carry;
    			if(t < 2){
    				c.insert(c.begin(), t + '0');
    				carry = 0;
    			}
    			else {
    				c.insert(c.begin(), t % 2 + '0');
    				carry = 1;
    			}
    		}
    		if(carry) c.insert(c.begin(), '1');
    		return c;
    	}
    };
    

Log in to reply
 

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