-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAddStrings.java
40 lines (32 loc) · 1.05 KB
/
AddStrings.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
37
38
39
40
package problems.leetcode;
/**
* https://leetcode.com/problems/add-strings/
*/
public class AddStrings {
public static void main(String[] args) {
String num1 = "123";
String num2 = "99";
System.out.println(addStrings(num1, num2));
}
public static String addStrings(String num1, String num2) {
num1 = new StringBuilder(num1).reverse().toString();
num2 = new StringBuilder(num2).reverse().toString();
StringBuilder res = new StringBuilder();
int carry = 0;
for (int i = 0, j = Math.max(num1.length(), num2.length()); i < j; i++) {
int n1 = i < num1.length() ? num1.charAt(i) - '0' : 0, n2 = i < num2.length() ? num2.charAt(i) - '0' : 0;
int sum = carry + n1 + n2;
if (sum >= 10) {
sum -= 10;
carry = 1;
} else {
carry = 0;
}
res.append(sum);
}
if (carry > 0) {
res.append(carry);
}
return res.reverse().toString();
}
}