Skip to content

Commit 569a6fc

Browse files
committed
Add AddStrings task solution
1 parent c5b7273 commit 569a6fc

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package by.andd3dfx.numeric;
2+
3+
/**
4+
* <pre>
5+
* <a href="https://leetcode.com/problems/add-strings/">Task description</a>
6+
*
7+
* Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
8+
*
9+
* You must solve the problem without using any built-in library for handling large integers (such as BigInteger).
10+
* You must also not convert the inputs to integers directly.
11+
*
12+
* Example 1:
13+
* Input: num1 = "11", num2 = "123"
14+
* Output: "134"
15+
*
16+
* Example 2:
17+
* Input: num1 = "456", num2 = "77"
18+
* Output: "533"
19+
*
20+
* Example 3:
21+
* Input: num1 = "0", num2 = "0"
22+
* Output: "0"
23+
* </pre>
24+
*/
25+
public class AddStrings {
26+
27+
public static String addStrings(String num1, String num2) {
28+
var chars1 = num1.toCharArray();
29+
var i = chars1.length - 1;
30+
31+
var chars2 = num2.toCharArray();
32+
var j = chars2.length - 1;
33+
34+
var sb = new StringBuilder();
35+
var accumulator = 0;
36+
while (i >= 0 && j >= 0) {
37+
int n1 = chars1[i] - '0';
38+
int n2 = chars2[j] - '0';
39+
40+
var res = n1 + n2 + accumulator;
41+
accumulator = 0;
42+
if (res <= 9) {
43+
sb.append(res);
44+
} else {
45+
sb.append(res % 10);
46+
res = res / 10;
47+
accumulator = res;
48+
}
49+
50+
i--;
51+
j--;
52+
}
53+
while (i >= 0) {
54+
int n1 = chars1[i] - '0' + accumulator;
55+
accumulator = 0;
56+
sb.append(n1);
57+
i--;
58+
}
59+
while (j >= 0) {
60+
int n2 = chars2[j] - '0' + accumulator;
61+
accumulator = 0;
62+
sb.append(n2);
63+
j--;
64+
}
65+
66+
return sb.reverse().toString();
67+
}
68+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package by.andd3dfx.numeric;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class AddStringsTest {
8+
9+
@Test
10+
public void addStrings() {
11+
assertThat(AddStrings.addStrings("11", "123")).isEqualTo("134");
12+
assertThat(AddStrings.addStrings("456", "77")).isEqualTo("533");
13+
assertThat(AddStrings.addStrings("0", "0")).isEqualTo("0");
14+
assertThat(AddStrings.addStrings("79", "179")).isEqualTo("258");
15+
}
16+
}

0 commit comments

Comments
 (0)