Skip to content

Commit f2eb7f8

Browse files
committed
415.字符串相加
1 parent 310a666 commit f2eb7f8

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
392. 判断子序列
7878
402. 移掉 K 位数字
7979
406. 根据身高重建队列
80+
415. 字符串相加
8081
416. 分割等和子集
8182
437. 路径总和
8283
448. 找到所有数组中消失的数字

leetcode_Java/Solution0415.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// 415. 字符串相加
2+
3+
4+
/*
5+
模拟竖式加法,从最低位开始两数相加,和超过10则向高位进一位,其中一个数字遍历结束了则需要补0
6+
*/
7+
class Solution {
8+
public String addStrings(String num1, String num2) {
9+
int i = num1.length() - 1;
10+
int j = num2.length() - 1;
11+
int carry = 0;
12+
StringBuilder res = new StringBuilder();
13+
while (i >= 0 || j >= 0 || carry > 0) {
14+
int x = i >= 0 ? num1.charAt(i--) - '0' : 0;
15+
int y = j >= 0 ? num2.charAt(j--) - '0' : 0;
16+
int sum = x + y + carry;
17+
carry = sum / 10;
18+
res.append(sum % 10);
19+
}
20+
return res.reverse().toString();
21+
}
22+
}

0 commit comments

Comments
 (0)