Skip to content

Commit 45ce5d8

Browse files
Add Strings
1 parent fdbde60 commit 45ce5d8

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

EASY/src/easy/AddStrings.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package easy;
2+
3+
/**
4+
* Created by fishercoder1534 on 10/9/16.
5+
*/
6+
public class AddStrings {
7+
8+
public static String addStrings(String num1, String num2) {
9+
if(num1 == null || num1.length() == 0) return num2;
10+
else if(num2 == null || num2.length() == 0) return num1;
11+
12+
int i = num1.length()-1, j = num2.length()-1;
13+
long carry = 0, sum = 0;
14+
StringBuilder sb = new StringBuilder();
15+
char[] char1 = num1.toCharArray();
16+
char[] char2 = num2.toCharArray();
17+
while(i >= 0 || j >= 0){
18+
sum = carry;
19+
if(i >= 0) sum += Character.getNumericValue(char1[i--]);
20+
if(j >= 0) sum += Character.getNumericValue(char2[j--]);
21+
carry = sum/10;
22+
sb.append(sum%10);
23+
}
24+
if(carry != 0) sb.append(carry);
25+
26+
return sb.reverse().toString();
27+
}
28+
29+
public static void main(String...args){
30+
// String num1 = "123";
31+
// String num2 = "34567";
32+
33+
// String num1 = "1";
34+
// String num2 = "9";
35+
36+
String num1 = "9";
37+
String num2 = "99";
38+
System.out.println(addStrings(num1, num2));
39+
}
40+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# fishercoderLeetcode
22
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
33
|-----|--------------------------|---------------------|-------|--------|------------|-----|------
4+
|415|[Add Strings](https://leetcode.com/problems/add-strings/)|[Solution](../../blob/master/EASY/src/easy/AddStrings.java)| O(n)|O(1) | Easy|
45
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)|[Solution](../../blob/master/EASY/src/easy/IntersectionOfTwoArraysII.java)| O(m+n)|O((m+n)) could be optimized | Easy| HashMap, Binary Search
56
|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)|[Solution](../../blob/master/EASY/src/easy/IntersectionOfTwoArrays.java)| O(m+n)|O(min(m,n)) | Easy| Two Pointers, Binary Search
67
|325|[Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/)|[Solution] | O(n)|O(n) | Medium| HashMap

0 commit comments

Comments
 (0)