leetcode-415-Add-Strings

描述


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

Note:

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

分析


解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public String addStrings(String num1, String num2) {
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
String result = "";
while (i >= 0 || j >= 0) {
if (i >= 0) {
carry += num1.charAt(i) - '0';
i--;
}
if (j >= 0) {
carry += num2.charAt(j) - '0';
j--;
}
result = Integer.toString(carry % 10) + result;
carry /= 10;
}
return carry != 0 ? "1" + result: result;
}
}

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func addStrings(num1 string, num2 string) string {
carry := 0
result := ""

for i, j := len(num1)-1, len(num2)-1; i >= 0 || j >= 0 || carry !=0; {
var x, y int
if i >= 0 {
x += int(num1[i] - '0')
}
if j >= 0 {
y += int(num2[j] - '0')
}
now := x + y + carry
result = strconv.Itoa(now % 10) + result
carry = now / 10
i--
j--
}
return result
}

相关问题


题目来源