My 3ms C++ solution


  • 0
    P
    class Solution {
    public:
        string addStrings(string num1, string num2) {
        	// initialize
            string result;
        	int size = max(num1.size(), num2.size()) + 1;
            num1.insert(num1.begin(), size - num1.size(), 48);
            num2.insert(num2.begin(), size - num2.size(), 48);
            result.insert(result.begin(), size, 48);
    
            // start calculation
            while (--size) {
                result[size - 1] += (num1[size] + num2[size] + result[size] - 144) / 10;
                result[size] = (num1[size] + num2[size] + result[size] - 144) % 10 + 48;
    	}
    
    	// erase the leading zero if exists
    	if (result.size() > 1 && result[0] == 48)
    	    result.erase(result.begin());
    
    	return result;
        }
    };
    

Log in to reply
 

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