File tree Expand file tree Collapse file tree 2 files changed +12
-32
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +12
-32
lines changed Original file line number Diff line number Diff line change 3
3
public class _415 {
4
4
5
5
public static class Solution1 {
6
+ /**
7
+ * My completely original solution on 10/14/2021.
8
+ */
6
9
public String addStrings (String num1 , String num2 ) {
7
- if (num1 == null || num1 .length () == 0 ) {
8
- return num2 ;
9
- } else if (num2 == null || num2 .length () == 0 ) {
10
- return num1 ;
11
- }
12
-
10
+ StringBuilder sb = new StringBuilder ();
13
11
int i = num1 .length () - 1 ;
14
12
int j = num2 .length () - 1 ;
15
- long carry = 0 ;
16
- long sum = 0 ;
17
- StringBuilder sb = new StringBuilder ();
18
- char [] char1 = num1 .toCharArray ();
19
- char [] char2 = num2 .toCharArray ();
13
+ int carry = 0 ;
20
14
while (i >= 0 || j >= 0 ) {
21
- sum = carry ;
15
+ int sum = carry ;
22
16
if (i >= 0 ) {
23
- sum += Character .getNumericValue (char1 [ i --] );
17
+ sum += Character .getNumericValue (num1 . charAt ( i ) );
24
18
}
25
19
if (j >= 0 ) {
26
- sum += Character .getNumericValue (char2 [ j --] );
20
+ sum += Character .getNumericValue (num2 . charAt ( j ) );
27
21
}
28
- carry = sum / 10 ;
29
22
sb .append (sum % 10 );
23
+ carry = sum / 10 ;
24
+ i --;
25
+ j --;
30
26
}
31
- if (carry != 0 ) {
27
+ if (carry > 0 ) {
32
28
sb .append (carry );
33
29
}
34
-
35
30
return sb .reverse ().toString ();
36
31
}
37
32
}
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 .Before ;
5
4
import org .junit .BeforeClass ;
6
5
import org .junit .Test ;
7
6
@@ -23,45 +22,31 @@ public static void setup() {
23
22
num2 = new String ();
24
23
}
25
24
26
- @ Before
27
- public void setupForEachTest () {
28
- expected = "" ;
29
- actual = "" ;
30
- num1 = "" ;
31
- num2 = "" ;
32
- }
33
-
34
25
@ Test
35
26
public void test1 () {
36
-
37
27
num1 = "123" ;
38
28
num2 = "34567" ;
39
29
expected = "34690" ;
40
30
actual = solution1 .addStrings (num1 , num2 );
41
31
assertEquals (expected , actual );
42
-
43
32
}
44
33
45
34
@ Test
46
35
public void test2 () {
47
-
48
36
num1 = "1" ;
49
37
num2 = "9" ;
50
38
expected = "10" ;
51
39
actual = solution1 .addStrings (num1 , num2 );
52
40
assertEquals (expected , actual );
53
-
54
41
}
55
42
56
43
@ Test
57
44
public void test3 () {
58
-
59
45
num1 = "9" ;
60
46
num2 = "99" ;
61
47
expected = "108" ;
62
48
actual = solution1 .addStrings (num1 , num2 );
63
49
assertEquals (expected , actual );
64
-
65
50
}
66
51
67
52
}
You can’t perform that action at this time.
0 commit comments