-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddString.java
33 lines (28 loc) · 873 Bytes
/
AddString.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
public class AddString {
// my solution_Runtime Error
public String addStrings(String num1, String num2) {
return String.valueOf(Integer.parseInt(num1) + Integer.parseInt(num2));
}
}
/* best solution
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder res = new StringBuilder();
int carry = 0;
int p1 = num1.length() - 1;
int p2 = num2.length() - 1;
while (p1 >= 0 || p2 >= 0) {
int x1 = p1 >= 0 ? num1.charAt(p1) - '0' : 0;
int x2 = p2 >= 0 ? num2.charAt(p2) - '0' : 0;
int value = (x1 + x2 + carry) % 10;
carry = (x1 + x2 + carry) / 10;
res.append(value);
p1--;
p2--;
}
if (carry != 0)
res.append(carry);
return res.reverse().toString();
}
}
*/