LeetCode415 - Add Strings 用字符串模拟整数相加
415. 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.
思路:控制num1的长度不小于num2的长度,在num1上直接做修改。
class Solution { public: string addStrings(string num1, string num2) { int len1 = num1.size(), len2 = num2.size(); if (len2 > len1) { swap(len1, len2); swap(num1, num2); } int i = len1 - 1, j = len2 - 1; int carry = 0, a = 0, b = 0, sum = 0; while (i >= 0) { a = num1[i] - '0'; if (j >= 0) b = num2[j] - '0'; else b = 0; sum = a + b + carry; if (sum >= 10) { sum -= 10; carry = 1; } else carry = 0; num1[i] = sum + '0'; --i;--j; } if (carry == 1) num1 = '1' + num1; return num1; } };