Skip to content

Commit 60db0a6

Browse files
committed
feat(leetcode): add No.415
1 parent e22af16 commit 60db0a6

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

415.Add-Strings.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// https://leetcode.com/problems/add-strings/
2+
//
3+
// algorithms
4+
// Easy (44.7%)
5+
// Total Accepted: 114,595
6+
// Total Submissions: 256,348
7+
8+
9+
class Solution {
10+
public String addStrings(String num1, String num2) {
11+
int len1 = num1.length(), len2 = num2.length();
12+
if (len1 == 0) {
13+
return num2;
14+
}
15+
if (len2 == 0) {
16+
return num1;
17+
}
18+
19+
LinkedList<Integer> l = new LinkedList<>();
20+
21+
int idx1 = 0, idx2 = 0, carry = 0;
22+
while (idx1 < len1 || idx2 < len2) {
23+
int tmp = carry;
24+
if (idx1 < len1) {
25+
tmp += (num1.charAt(len1 - 1 - idx1) - '0');
26+
idx1++;
27+
}
28+
if (idx2 < len2) {
29+
tmp += (num2.charAt(len2 - 1 - idx2) - '0');
30+
idx2++;
31+
}
32+
33+
if (tmp >= 10) {
34+
carry = 1;
35+
tmp -= 10;
36+
} else {
37+
carry = 0;
38+
}
39+
40+
l.addFirst(tmp);
41+
}
42+
43+
if (carry == 1) {
44+
l.addFirst(1);
45+
}
46+
47+
StringBuilder sb = new StringBuilder();
48+
for (int n : l) {
49+
sb.append(n);
50+
}
51+
52+
return sb.toString();
53+
}
54+
}

0 commit comments

Comments
 (0)