655. Add Strings
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Example
Example 1:
Input : num1 = "123", num2 = "45"
Output : "168"
Notice
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
解法1:
class Solution {
public:
/**
* @param num1: a non-negative integers
* @param num2: a non-negative integers
* @return: return sum of num1 and num2
*/
string addStrings(string &num1, string &num2) {
//return to_string(stoi(num1) + stoi(num2));
int n1 = num1.size();
int p1 = n1 - 1;
int n2 = num2.size();
int p2 = n2 - 1;
int sum = 0, carry = 0;
string result = "";
while(p1 >= 0 && p2 >= 0) {
sum = num1[p1] - '0' + num2[p2] - '0' + carry;
carry = sum / 10;
result = to_string(sum % 10) + result;
p1--; p2--;
}
int p = -1; string num;
if (p1 >= 0) {
p = p1; num = num1;
} else if (p2 >= 0) {
p = p2; num = num2;
}
if (p < 0) return carry > 0 ? '1' + result : result;
while (p >= 0) {
sum = num[p] - '0' + carry;
carry = sum / 10;
result = to_string(sum % 10) + result;
p--;
}
return carry > 0 ? '1' + result : result;
}
};
发一个C的版本
#define MAX(a, b) (a > b ? a : b)
char* addStrings(char* num1, char* num2) {
int len1 = (int)strlen(num1), len2 = (int)strlen(num2);
int len3 = MAX(len1, len2) + 2;
int index1 = len1 - 1, index2 = len2 - 1, index3 = len3 - 2;
int carry = 0, sum = 0;
char *res = (char *)malloc(len3);
memset(res, 0, len3);
while (index1 >= 0 || index2 >= 0) {
sum = carry;
if (index1 >= 0) sum += num1[index1--] - '0';
if (index2 >= 0) sum += num2[index2--] - '0';
carry = sum / 10;
res[index3--] = '0' + (sum % 10);
}
if (carry > 0) {
res[index3--] = '1';
}
if (res[0] == 0) return &res[1];
return res;
}