Can you write a more effictive code with cpp? I hope so


  • 1
    J
    string addBinary(string a, string b) {
    	string sum;
    	int alength = a.length (), blength = b.length ();
    	int sval = 0, aval = 0, bval = 0;
    
    	while (alength != 0 || blength != 0) {
    		aval = getLastVal (a, alength);
    		bval = getLastVal (b, blength);
    
    		sval = aval + bval + sval;
    		sum = (sval % 2 == 1 ? '1' : '0') + sum;
    		sval = sval / 2;
    	}
    
    	if (sval == 1) {
    		sum = '1' + sum;
    	}
    	
    	return sum;
    }
    
    int getLastVal (const string& str, int& length)
    {
    	if (length == 0) {
    		return 0;
    	} 
    	else {
    		char b = str.at (length - 1);
    		length = length - 1;
    		return (int)(b - '0');
    	}
    }

  • 1
    T

    I think my solution is more efficient than yours.

    class Solution {
    public:
        string addBinary(string a, string b) {
            string re;
    
            reverse(a.begin(), a.end());
            reverse(b.begin(), b.end());
            int pos = 0;
            int carry = 0;
            while(pos < a.size() && pos < b.size()) {  
                int cur  = carry + a[pos] - '0' + b[pos] - '0';
                carry = cur/2;
                re.insert(re.begin(), '0'+cur%2);
                pos++;
            }
            string remain;
            if(pos == a.size())
                remain = b;
            else
                remain = a;
            for(int i = pos; pos < remain.size(); pos++) {
                int cur  = carry + remain[pos] - '0';
                carry = cur/2;
                re.insert(re.begin(), '0'+(cur%2));
            }
            if(carry)
                re.insert(re.begin(), '1');
    
            return re;
        }
    };
    

Log in to reply
 

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