Skip to content

Commit 41e5bd5

Browse files
refactor 415
1 parent b4f97ed commit 41e5bd5

File tree

2 files changed

+12
-32
lines changed

2 files changed

+12
-32
lines changed

src/main/java/com/fishercoder/solutions/_415.java

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,30 @@
33
public class _415 {
44

55
public static class Solution1 {
6+
/**
7+
* My completely original solution on 10/14/2021.
8+
*/
69
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();
1311
int i = num1.length() - 1;
1412
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;
2014
while (i >= 0 || j >= 0) {
21-
sum = carry;
15+
int sum = carry;
2216
if (i >= 0) {
23-
sum += Character.getNumericValue(char1[i--]);
17+
sum += Character.getNumericValue(num1.charAt(i));
2418
}
2519
if (j >= 0) {
26-
sum += Character.getNumericValue(char2[j--]);
20+
sum += Character.getNumericValue(num2.charAt(j));
2721
}
28-
carry = sum / 10;
2922
sb.append(sum % 10);
23+
carry = sum / 10;
24+
i--;
25+
j--;
3026
}
31-
if (carry != 0) {
27+
if (carry > 0) {
3228
sb.append(carry);
3329
}
34-
3530
return sb.reverse().toString();
3631
}
3732
}
Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.fishercoder;
22

33
import com.fishercoder.solutions._415;
4-
import org.junit.Before;
54
import org.junit.BeforeClass;
65
import org.junit.Test;
76

@@ -23,45 +22,31 @@ public static void setup() {
2322
num2 = new String();
2423
}
2524

26-
@Before
27-
public void setupForEachTest() {
28-
expected = "";
29-
actual = "";
30-
num1 = "";
31-
num2 = "";
32-
}
33-
3425
@Test
3526
public void test1() {
36-
3727
num1 = "123";
3828
num2 = "34567";
3929
expected = "34690";
4030
actual = solution1.addStrings(num1, num2);
4131
assertEquals(expected, actual);
42-
4332
}
4433

4534
@Test
4635
public void test2() {
47-
4836
num1 = "1";
4937
num2 = "9";
5038
expected = "10";
5139
actual = solution1.addStrings(num1, num2);
5240
assertEquals(expected, actual);
53-
5441
}
5542

5643
@Test
5744
public void test3() {
58-
5945
num1 = "9";
6046
num2 = "99";
6147
expected = "108";
6248
actual = solution1.addStrings(num1, num2);
6349
assertEquals(expected, actual);
64-
6550
}
6651

6752
}

0 commit comments

Comments
 (0)