forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Strings.java
More file actions
20 lines (20 loc) · 772 Bytes
/
Add Strings.java
File metadata and controls
20 lines (20 loc) · 772 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String addStrings(String num1, String num2) {
int carry = 0;
StringBuilder sb = new StringBuilder();
int idxOne = num1.length() - 1;
int idxTwo = num2.length() - 1;
while (idxOne >= 0 || idxTwo >= 0 || carry > 0) {
if (idxOne >= 0 && idxTwo >= 0) {
carry += Character.getNumericValue(num1.charAt(idxOne--)) + Character.getNumericValue(num2.charAt(idxTwo--));
} else if (idxOne >= 0 && idxTwo < 0) {
carry += Character.getNumericValue(num1.charAt(idxOne--));
} else if (idxOne < 0 && idxTwo >= 0) {
carry += Character.getNumericValue(num2.charAt(idxTwo--));
}
sb.append(carry % 10);
carry = carry > 9 ? carry / 10 : 0;
}
return sb.reverse().toString();
}
}