#2243
Easy Algorithms Calculate digit sum of a string
String Simulation
67.7% acceptance
Feb 25, 2026
595
52
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 s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.
Replace each group of s with 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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn digit_sum(s: String, k: i32) -> String {
let k = k as usize;
let mut s = s;
while s.len() > k {
let chars: Vec<char> = s.chars().collect();
let mut new_s = String::new();
for chunk in chars.chunks(k) {
let sum: u32 = chunk.iter().map(|&c| c as u32 - '0' as u32).sum();
new_s.push_str(&sum.to_string());
}
s = new_s;
}
s
}
}