[LeetCode] Add Strings
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.
给定两个只含有数字字符串,将字符串中的数字和返回一个字符串。并且要求不能使用整数类库及将输入直接转换成整数。这需要对两个字符串中数字对位相加并处理相加所得的进位。每完成一位的数相加,把它放去结果字符串中。最后将所得的结果字符串数组反转即可。
class Solution { public: string addStrings(string num1, string num2) { string s; int carry = 0; int i = num1.size() - 1; int j = num2.size() - 1; while (i >= 0 || j >= 0 || carry) { int sum = 0; if (i >= 0) { sum = sum + num1[i] - '0'; i--; } if (j >= 0) { sum = sum + num2[j] - '0'; j--; } sum = sum + carry; carry = sum / 10; sum = sum % 10; s = s + to_string(sum); } reverse(s.begin(), s.end()); return s; } }; // 16 ms