-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddStrings.java
More file actions
50 lines (40 loc) · 1.2 KB
/
Copy pathAddStrings.java
File metadata and controls
50 lines (40 loc) · 1.2 KB
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
41
42
43
44
45
46
47
48
49
50
package org.example;
public class AddStrings {
public String addStrings(String num1, String num2) {
int p = num1.length() - 1;
int q = num2.length() - 1;
int carry = 0;
StringBuilder result = new StringBuilder();
while (p >= 0 && q >= 0) {
int n1 = num1.charAt(p) - '0';
int n2 = num2.charAt(q) - '0';
int sum = (n1 + n2 + carry) % 10;
carry = (n1 + n2 + carry) / 10;
// result.insert(0, sum);
result.append(sum);
p--;
q--;
}
while (p >= 0) {
int n1 = num1.charAt(p) - '0';
int sum = (n1 + carry) % 10;
carry = (n1 + carry) / 10;
p--;
// result.insert(0, sum);
result.append(sum);
}
while (q >= 0) {
int n2 = num2.charAt(q) - '0';
int sum = (n2 + carry) % 10;
carry = (n2 + carry) / 10;
q--;
// result.insert(0, sum);
result.append(sum);
}
if (carry > 0) {
// result.insert(0, '1');
result.append('1');
}
return result.reverse().toString();
}
}