С++ solution (19ms) , minimum of built-in functions


  • 0
    A
    string addStrings(string num1, string num2) {
    	string positionSum;
    	string result;
    	char carry = 0;
    	string positionCarry;
    	char sum;
    	while (num1.length() > num2.length())
    	{
    		num2.insert(0, "0");
    	}
    
    	while (num1.length() < num2.length())
    	{
    		num1.insert(0, "0");
    	}
    
    	for (int i = num1.length() - 1; i >= 0; i--)
    	{
    		sum = num1[i] - 48 + num2[i] - 48;
    		carry = sum / 10;
    		sum %= 10;
    		positionSum.insert(0, to_string(sum));
    		positionCarry.insert(0, to_string(carry));
    	}
    
    	int i = positionSum.length() - 2;
    	int j = positionCarry.length() - 1;
    	result.insert(0, to_string(positionSum[positionSum.length() - 1]-48 ));
    	for (;  ;i--)
    	{
    		if (i == -1 && j == 0)
    		{
    			if (positionCarry[0] - 48 != 0)
    			{
    				result.insert(0, to_string(positionCarry[0]-48));
    			}
    			break;
    		}
    		sum = positionCarry[j] - 48 + positionSum[i] - 48;
    		carry = sum / 10;
    		sum %= 10;
    		positionCarry[i] += carry;
    		result.insert(0, to_string(sum));
    		j--;
    	}
    
    	return result;
    }
    

Log in to reply
 

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