Skip to content

Commit f7d24ca

Browse files
solves #2243: Calculate Digit Sum of a String in java
1 parent 076f086 commit f7d24ca

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -729,7 +729,7 @@
729729
| 2235 | [Add Two Integers](https://leetcode.com/problems/add-two-integers) | [![Java](assets/java.png)](src/AddTwoIntegers.java) | |
730730
| 2236 | [Root Equals Sum of Children](https://leetcode.com/problems/root-equals-sum-of-children) | [![Java](assets/java.png)](src/RootEqualsSumOfChildren.java) | |
731731
| 2239 | [Find Closest Number to Zero](https://leetcode.com/problems/find-closest-number-to-zero) | [![Java](assets/java.png)](src/FindClosestNumberToZero.java) | |
732-
| 2243 | [Calculate Digit Sum of a String](https://leetcode.com/problems/calculate-digit-sum-of-a-string) | | |
732+
| 2243 | [Calculate Digit Sum of a String](https://leetcode.com/problems/calculate-digit-sum-of-a-string) | [![Java](assets/java.png)](src/CalculateDigitSumOfAString.java) | |
733733
| 2248 | [Intersection of Multiple Arrays](https://leetcode.com/problems/intersection-of-multiple-arrays) | | |
734734
| 2255 | [Count Prefixes of a Given String](https://leetcode.com/problems/count-prefixes-of-a-given-string) | | |
735735
| 2259 | [Remove Digit From Number to Maximize Result](https://leetcode.com/problems/remove-digit-from-number-to-maximize-result) | | |

src/CalculateDigitSumOfAString.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// https://leetcode.com/problems/calculate-digit-sum-of-a-string
2+
// T: O(log(n))
3+
// S: O(log(n))
4+
5+
public class CalculateDigitSumOfAString {
6+
public String digitSum(String s, int k) {
7+
if (s.length() <= k) return s;
8+
final StringBuilder result = new StringBuilder();
9+
for (int i = 0 ; i < s.length() ; i += k) {
10+
final String group = s.substring(i, Math.min(i + k, s.length()));
11+
final int groupSum = digitSum(group);
12+
result.append(groupSum);
13+
}
14+
return digitSum(result.toString(), k);
15+
}
16+
17+
private int digitSum(String number) {
18+
int sum = 0;
19+
for (int index = 0 ; index < number.length() ; index++) {
20+
sum += toInt(number.charAt(index));
21+
}
22+
return sum;
23+
}
24+
25+
private int toInt(char x) {
26+
return x - '0';
27+
}
28+
}

0 commit comments

Comments
 (0)