Calculate Digit Sum of a String - Problem
You are given a string s consisting of digits and an integer k.
A round can be completed if the length of s is greater than k. In one round, do the following:
- Divide
sinto consecutive groups of sizeksuch that the firstkcharacters are in the first group, the nextkcharacters are in the second group, and so on. Note that the size of the last group can be smaller thank. - Replace each group of
swith a string representing the sum of all its digits. For example,"346"is replaced with"13"because 3 + 4 + 6 = 13. - Merge consecutive groups together to form a new string. If the length of the string is greater than
k, repeat from step 1.
Return s after all rounds have been completed.
Input & Output
Example 1 — Basic Case
$
Input:
s = "11111222223", k = 3
›
Output:
"135"
💡 Note:
Round 1: "111"|"112"|"222"|"23" → "3"|"4"|"6"|"5" → "3465". Round 2: "346"|"5" → "13"|"5" → "135". Length 3 ≤ k=3, so return "135".
Example 2 — Single Round
$
Input:
s = "00000000", k = 3
›
Output:
"000"
💡 Note:
Round 1: "000"|"000"|"00" → "0"|"0"|"0" → "000". Length 3 ≤ k=3, so return "000".
Example 3 — No Processing Needed
$
Input:
s = "123", k = 4
›
Output:
"123"
💡 Note:
Length 3 ≤ k=4, so no rounds needed. Return original string "123".
Constraints
- 1 ≤ s.length ≤ 100
- 1 ≤ k ≤ 100
- s consists of only digits
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s and group size k
2
Process
Iteratively group and sum digits
3
Output
Final string when length ≤ k
Key Takeaway
🎯 Key Insight: Keep grouping digits by size k and summing until the result is short enough
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code