題目
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
題解
這題很明顯就是一個字符串的大數相加。
首先相同位數的相加,然後考慮一下進位符。
如果一個數沒有第k位,那麼和的第k位就是另一個數的第k位和進位符相加。
最後需要注意以下最後會不會有多出一個進位。
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.size() - 1;
int j = num2.size() - 1;
string s;
int k = 0;
while(i >= 0 || j >= 0) {
int t = k;
if (i < 0) {
t += num2[j] - '0';
} else if (j < 0) {
t += num1[i] - '0';
} else {
t += num2[j] + num1[i] - '0' - '0';
}
k = t / 10;
char c = '0' + t % 10;
s = c + s;
i--;
j--;
}
if (k > 0) {
s = "1" + s;
}
return s;
}
};