Star

LeetCode 415. Add Strings

Question

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  • The length of both num1 and num2 is < 5100.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

Explanation

得到两个用String表示的数的和。不能直接转成int再加,会有overflow的问题。所以一位一位地加,计算进位,用stringbuilder得到最后的结果。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0;
int i=num1.length()-1; int j=num2.length()-1;
int a = 0; int b=0;
while (i >=0 || j>=0 || carry >= 1) {
if (i >= 0) {
a = num1.toCharArray()[i--] - '0';
} else {
a = 0;
}
if (j >= 0) {
b = num2.toCharArray()[j--] - '0';
} else {
b = 0;
}
int sum = a+b+carry;
carry = sum/10;
sb.insert(0,sum%10);
}
return sb.toString();
}
}