-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_415_add_strings.java
More file actions
61 lines (54 loc) · 1.47 KB
/
Copy path_415_add_strings.java
File metadata and controls
61 lines (54 loc) · 1.47 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
51
52
53
54
55
56
57
58
59
60
61
public class _415_add_strings {
public static String addStrings(String num1, String num2) {
char[] a1 = num1.toCharArray();
char[] a2 = num2.toCharArray();
int n1 = a1.length;
int n2 = a2.length;
int i = 0;
int debt = 0;
String result = "";
while (i < n1 && i < n2) {
int sum = a1[n1-1-i] + a2[n2-1-i] + debt - 2 * 48;
if (sum > 9) {
sum -= 10;
debt = 1;
} else {
debt = 0;
}
result = String.valueOf(sum) + result;
i++;
}
while (i < n1) {
int sum = a1[n1-1-i] + debt - 48;
if (sum > 9) {
sum -= 10;
debt = 1;
} else {
debt = 0;
}
result = String.valueOf(sum) + result;
i++;
}
while (i < n2) {
int sum = a2[n2-1-i] + debt - 48;
if (sum > 9) {
sum -= 10;
debt = 1;
} else {
debt = 0;
}
result = String.valueOf(sum) + result;
i++;
}
if (debt == 1) {
result = "1" + result;
}
return result;
}
public static void main(String[] args) {
String num1 = "1";
String num2 = "9";
String result = addStrings(num1, num2);
System.out.println(result);
}
}