-
Notifications
You must be signed in to change notification settings - Fork 1
/
Add Strings
73 lines (61 loc) · 1.67 KB
/
Add Strings
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
62
63
64
65
66
67
68
69
70
71
72
73
import java.lang.Math;
class Solution {
public String addStrings(String num1, String num2) {
int carry = 0;
int first = 0;
int second = 0;
int result = 0;
String min = "";
String max = "";
String sum = "";
if(num1.length()>num2.length()){
min = num2;
max = num1;
}
else{
max = num2;
min = num1;
}
for(int i = 0; i<min.length(); i++){
first = min.charAt(min.length()-i-1) - '0';
second = max.charAt(max.length()-i-1) - '0';
result = first + second + carry;
if(result < 10){
sum += "" + result;
carry = 0;
}
else{
sum += result - 10 + "";
carry = 1;
}
}
if(max.length() == min.length()){
if(carry == 1){
sum += "" + 1;
}
return reverse(sum);
}
for(int i = max.length()-min.length()-1; i>=0; i--){
result = (max.charAt(i) - '0') + carry;
if(result < 10){
sum += result;
carry = 0;
}
else{
sum += result - 10 + "";
carry = 1;
}
}
if(carry == 1){
sum += "1";
}
return reverse(sum);
}
public static String reverse(String a){
String sum = "";
for(int i = a.length()-1; i>= 0; i--){
sum += a.charAt(i) + "";
}
return sum;
}
}