File tree 2 files changed +35
-9
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +35
-9
lines changed Original file line number Diff line number Diff line change @@ -31,4 +31,30 @@ public String addStrings(String num1, String num2) {
31
31
}
32
32
}
33
33
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
+
34
60
}
Original file line number Diff line number Diff line change 1
1
package com .fishercoder ;
2
2
3
3
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 ;
6
6
7
- import static junit .framework . Assert .assertEquals ;
7
+ import static org . junit .jupiter . api . Assertions .assertEquals ;
8
8
9
9
public class _415Test {
10
10
private static _415 .Solution1 solution1 ;
11
+ private static _415 .Solution2 solution2 ;
11
12
private static String expected ;
12
13
private static String actual ;
13
14
private static String num1 ;
14
15
private static String num2 ;
15
16
16
- @ BeforeClass
17
- public static void setup () {
17
+ @ BeforeEach
18
+ public void setup () {
18
19
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 ();
23
21
}
24
22
25
23
@ Test
@@ -29,6 +27,8 @@ public void test1() {
29
27
expected = "34690" ;
30
28
actual = solution1 .addStrings (num1 , num2 );
31
29
assertEquals (expected , actual );
30
+ actual = solution2 .addStrings (num1 , num2 );
31
+ assertEquals (expected , actual );
32
32
}
33
33
34
34
@ Test
You can’t perform that action at this time.
0 commit comments