LeetCode415-字符串相加

题目链接

英文链接:https://leetcode.com/problems/add-strings/

中文链接:https://leetcode-cn.com/problems/add-strings/

题目详述

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

  1. num1 和num2 的长度都小于 5100.
  2. num1 和num2 都只包含数字 0-9.
  3. num1 和num2 都不包含任何前导零。
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

题目详解

模拟竖式加法,LeetCode67-二进制求和 等题目都是类似的解法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LeetCode_00415 {

public String addStrings(String num1, String num2) {
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0;
StringBuilder res = new StringBuilder();
while (i >= 0 || j >= 0 || carry != 0) {
carry += (i >= 0 ? num1.charAt(i--) - '0' : 0) + (j >= 0 ? num2.charAt(j--) - '0' : 0);
res.append(carry % 10);
carry /= 10;
}
return res.reverse().toString();
}
}