forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddStrings.java
51 lines (40 loc) · 1.06 KB
/
AddStrings.java
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
class Solution {
// TC : O(len1+ len2)
public String addStrings(String num1, String num2) {
String ans = "";
int it1 = num1.length()-1;
int it2 = num2.length()-1;
int carry = 0;
int sum = 0;
while(it1>=0 && it2>=0){
int digit1 = num1.charAt(it1) -'0';
int digit2 = num2.charAt(it2) - '0';
sum = digit1 + digit2 + carry;
carry = sum/10;
sum = sum%10;
ans = sum + ans;
it1--;
it2--;
}
while(it1>=0){
int digit1 = num1.charAt(it1) -'0';
sum = digit1 + carry;
carry = sum/10;
sum = sum%10;
ans = sum + ans;
it1--;
}
while(it2>=0){
int digit2 = num2.charAt(it2) -'0';
sum = digit2 + carry;
carry = sum/10;
sum = sum%10;
ans = sum + ans;
it2--;
}
if(carry==1){
ans = "1"+ans ;
}
return ans;
}
}