Given two non-negative integers
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.
非常简单的题目,先把两个string reverse,这样才可以从头加到尾是从低位到高位,用一个sum, next表示当前的和,以及进位。while loop 判断有没有超过最大的string长度,以及进位是不是还有值没有处理。加完以后,再reverse string就是答案了。另外,处理string to int时,别忘了 +- ‘0’。
class Solution { public: string addStrings(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); int s1 = num1.size(), s2 = num2.size(); int i = 0, next = 0, sum = 0; string res; while(i < max(s1, s2) || next != 0) { sum += next; sum += i < s1 ? num1[i] - '0' : 0; sum += i < s2 ? num2[i] - '0': 0; res += sum % 10 + '0'; next = sum/10; sum = 0; i++; } reverse(res.begin(), res.end()); return res; } };
No comments:
Post a Comment