Skip to content

Commit 0f9be00

Browse files
authored
Update Add Strings.java
1 parent fc76913 commit 0f9be00

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

Easy/Add Strings.java

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,22 @@
11
class Solution {
22
public String addStrings(String num1, String num2) {
33
StringBuilder sb = new StringBuilder();
4-
int idx1 = num1.length() - 1;
5-
int idx2 = num2.length() - 1;
4+
int idxOne = num1.length() - 1;
5+
int idxTwo = num2.length() - 1;
66
int carry = 0;
7-
while (idx1 >= 0 || idx2 >= 0) {
7+
while (idxOne >= 0 || idxTwo >= 0 || carry > 0) {
88
int temp = carry;
9-
if (idx1 >= 0 && idx2 >= 0) {
10-
temp += Character.getNumericValue(num1.charAt(idx1--)) + Character.getNumericValue(num2.charAt(idx2--));
11-
}
12-
else if (idx1 >= 0 && idx2 < 0) {
13-
temp += Character.getNumericValue(num1.charAt(idx1--));
14-
}
15-
else {
16-
temp += Character.getNumericValue(num2.charAt(idx2--));
9+
if (idxOne >= 0 && idxTwo >= 0) {
10+
temp += Character.getNumericValue(num1.charAt(idxOne--)) + Character.getNumericValue(num2.charAt(idxTwo--));
11+
} else if (idxOne >= 0 && idxTwo < 0) {
12+
temp += Character.getNumericValue(num1.charAt(idxOne--));
13+
} else if (idxOne < 0 && idxTwo >= 0) {
14+
temp += Character.getNumericValue(num2.charAt(idxTwo--));
1715
}
1816
carry = temp > 9 ? 1 : 0;
1917
temp = temp > 9 ? temp % 10 : temp;
2018
sb.append(temp);
2119
}
22-
if (carry > 0) {
23-
sb.append(carry);
24-
}
2520
return sb.reverse().toString();
2621
}
2722
}

0 commit comments

Comments
 (0)