File tree Expand file tree Collapse file tree 2 files changed +84
-0
lines changed
main/java/by/andd3dfx/numeric
test/java/by/andd3dfx/numeric Expand file tree Collapse file tree 2 files changed +84
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments