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.
给定两个非负整数用字符串表示的非负整数num1和num2,求它们的和。
分析:
这题比较简单,将num1、num2按位相加,并计算进位即可。
代码如下:
string addStrings(string num1, string num2) { string rst; reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); int len1 = num1.length(); int len2 = num2.length(); int len = len1 > len2 ? len1 : len2; char last = 0; for (int i = 0; i < len; i++) { char ch = last; if (i < len1) ch += (num1[i] - '0'); if (i < len2) ch += (num2[i] - '0'); last = ch / 10; ch %= 10; rst += (ch + '0'); } if (last > 0) rst += (last + '0'); reverse(rst.begin(), rst.end()); return rst; }