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
22 lines (22 loc) · 819 Bytes
/
Add Strings.java
File metadata and controls
22 lines (22 loc) · 819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int idxOne = num1.length() - 1;
int idxTwo = num2.length() - 1;
int carry = 0;
while (idxOne >= 0 || idxTwo >= 0 || carry > 0) {
int temp = carry;
if (idxOne >= 0 && idxTwo >= 0) {
temp += Character.getNumericValue(num1.charAt(idxOne--)) + Character.getNumericValue(num2.charAt(idxTwo--));
} else if (idxOne >= 0 && idxTwo < 0) {
temp += Character.getNumericValue(num1.charAt(idxOne--));
} else if (idxOne < 0 && idxTwo >= 0) {
temp += Character.getNumericValue(num2.charAt(idxTwo--));
}
carry = temp > 9 ? 1 : 0;
temp = temp > 9 ? temp % 10 : temp;
sb.append(temp);
}
return sb.reverse().toString();
}
}