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.
1 class Solution { 2 public: 3 string addStrings(string num1, string num2) { 4 if (num1.size() < num2.size()) return addStrings(num2, num1); 5 int extra = 0; 6 int idx1 = num1.size() - 1; 7 int idx2 = num2.size() - 1; 8 while (idx1 >= 0) { 9 int sum = extra + num1[idx1] - '0'; 10 if (idx2 >= 0) 11 sum = sum + num2[idx2] - '0'; 12 num1[idx1] = '0' + sum % 10; 13 extra = sum / 10; 14 idx1--; 15 idx2--; 16 } 17 if (extra) num1 = "1" + num1; 18 return num1; 19 } 20 };