Skip to content

Commit e6b1210

Browse files
add a solution for 415
1 parent f782398 commit e6b1210

File tree

2 files changed

+35
-9
lines changed

2 files changed

+35
-9
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_415.java

+26
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,30 @@ public String addStrings(String num1, String num2) {
3131
}
3232
}
3333

34+
public static class Solution2 {
35+
/**
36+
* This is an optimized version of Solution1, on LeetCode, this version beats 100% while Solution1 beats only 67%.
37+
*/
38+
public String addStrings(String num1, String num2) {
39+
StringBuilder sb = new StringBuilder();
40+
int i = num1.length() - 1;
41+
int j = num2.length() - 1;
42+
int carry = 0;
43+
while (i >= 0 || j >= 0 || carry > 0) {
44+
int sum = carry;
45+
if (i >= 0) {
46+
sum += num1.charAt(i) - '0';
47+
}
48+
if (j >= 0) {
49+
sum += num2.charAt(j) - '0';
50+
}
51+
sb.append(sum % 10);
52+
carry = sum / 10;
53+
i--;
54+
j--;
55+
}
56+
return sb.reverse().toString();
57+
}
58+
}
59+
3460
}

Diff for: src/test/java/com/fishercoder/_415Test.java

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,23 @@
11
package com.fishercoder;
22

33
import com.fishercoder.solutions._415;
4-
import org.junit.BeforeClass;
5-
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
66

7-
import static junit.framework.Assert.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
88

99
public class _415Test {
1010
private static _415.Solution1 solution1;
11+
private static _415.Solution2 solution2;
1112
private static String expected;
1213
private static String actual;
1314
private static String num1;
1415
private static String num2;
1516

16-
@BeforeClass
17-
public static void setup() {
17+
@BeforeEach
18+
public void setup() {
1819
solution1 = new _415.Solution1();
19-
expected = new String();
20-
actual = new String();
21-
num1 = new String();
22-
num2 = new String();
20+
solution2 = new _415.Solution2();
2321
}
2422

2523
@Test
@@ -29,6 +27,8 @@ public void test1() {
2927
expected = "34690";
3028
actual = solution1.addStrings(num1, num2);
3129
assertEquals(expected, actual);
30+
actual = solution2.addStrings(num1, num2);
31+
assertEquals(expected, actual);
3232
}
3333

3434
@Test

0 commit comments

Comments
 (0)