问题来源:https://leetcode.com/problems/add-strings/
问题描述:Given two non-negative numbers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
我的代码(6ms):注意进位处理和判断条件即可。
string addStrings(string num1, string num2){
string result = "";
int digit1, digit2;
int carry = 0;
int i = num1.length() - 1;
int j = num2.length() - 1;
while (1){
if (i < 0 && j >= 0){
digit1 = 0;
digit2 = num2[j] - '0';
}
else if (j < 0 && i >= 0){
digit1 = num1[i] - '0';
digit2 = 0;
}
else if (i < 0 && j < 0){
break;
}
else{
digit1 = num1[i] - '0';
digit2 = num2[j] - '0';
}
result += (digit1 + digit2 + carry) % 10 + '0';
if (digit1 + digit2 + carry >= 10){
carry = 1;
} else{
carry = 0;
}
i--;
j--;
}
if (carry==1)
result += carry + '0';
reverse(result.begin(),result.end());
return result;
}
(3ms)简约风:
string addStrings(string num1, string num2) {
int i = num1.size() - 1, j = num2.size() - 1, carry = 0;
if (i < j) return addStrings(num2, num1);//减少判断条件
for (; (j >= 0 || carry) && i >= 0; carry /= 10) {
if (j >= 0) carry += num2[j--] - '0';
carry += num1[i] - '0';
num1[i--] = carry % 10 + '0';//减少空间 并且 避免反转
}
if (carry) return '1' + num1;
return num1;
}