Skip to content

Commit 85d7b74

Browse files
committed
2022-05-19 update: added "Calculate Digit Sum of a String"
1 parent 1f163bd commit 85d7b74

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
// https://leetcode.com/problems/calculate-digit-sum-of-a-string
7+
public class CalculateDigitSumOfAString {
8+
9+
private String s;
10+
private final int k;
11+
12+
public CalculateDigitSumOfAString(String s, int k) {
13+
this.s = s;
14+
this.k = k;
15+
}
16+
17+
public String solution() {
18+
while (s.length() > k) {
19+
List<String> groups = new ArrayList<>();
20+
for (int i = 0; i < s.length(); i += k) {
21+
groups.add(s.substring(i, i + Math.min(k, s.length() - i)));
22+
}
23+
StringBuilder newS = new StringBuilder();
24+
for (String group : groups) {
25+
int num = 0;
26+
for (int i = 0; i < group.length(); i++) {
27+
num += group.charAt(i) - '0';
28+
}
29+
newS.append(num);
30+
}
31+
s = newS.toString();
32+
}
33+
return s;
34+
}
35+
36+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class CalculateDigitSumOfAStringTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertEquals(
12+
"135",
13+
new CalculateDigitSumOfAString(
14+
"11111222223",
15+
3
16+
).solution()
17+
);
18+
}
19+
20+
}

0 commit comments

Comments
 (0)