415. 字符串相加

题目

给定两个字符串形式的非负整数 num1num2 ,计算它们的和并同样以字符串形式返回。

你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。

示例1:

1
2
输入:num1 = "11", num2 = "123"
输出:"134"

示例2:

1
2
输入:num1 = "456", num2 = "77"
输出:"533"

示例3:

1
2
输入:num1 = "0", num2 = "0"
输出:"0"

提示:

  • 1 <= num1.length, num2.length <= 104
  • num1num2 都只包含数字 0-9
  • num1num2 都不包含任何前导零

解法

解法一:

Java

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
26
27
28
29
30
31
32
33
34
35
36
public String addStrings(String num1, String num2) {
if (num1.length() > num2.length()) {
int diff = num1.length() - num2.length();
StringBuilder num2Builder = new StringBuilder(num2);
while (diff > 0) {
num2Builder.insert(0, "0");
diff--;
}
num2 = num2Builder.toString();
} else if (num2.length() > num1.length()) {
int diff = num2.length() - num1.length();
StringBuilder num1Builder = new StringBuilder(num1);
while (diff > 0) {
num1Builder.insert(0, "0");
diff--;
}
num1 = num1Builder.toString();
}

StringBuilder result = new StringBuilder();
int carry = 0;
for (int i = num1.length() - 1;i >= 0;i--) {
int sum = num1.charAt(i) - '0' + num2.charAt(i) - '0' + carry;
if (sum >= 10) {
sum -= 10;
carry = 1;
} else {
carry = 0;
}
result.append(sum);
}
if (carry == 1) {
result.append(carry);
}
return result.reverse().toString();
}

解法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
while (i >= 0 || j >= 0 || carry != 0) {
if (i >= 0) {
carry += num1.charAt(i--) - '0';
}
if (j >= 0) {
carry += num2.charAt(j--) - '0';
}
sb.append(carry % 10);
carry /= 10;
}
return sb.reverse().toString();
}
0%