LeetCode Entry
2243. Calculate Digit Sum of a String
Chunk-sum transform the string
2243. Calculate Digit Sum of a String easy substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1544
Problem TLDR
Chunk-sum transform the string
Intuition
Simulate brute-force.
Approach
- can use a recursion
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
fun digitSum(s: String, k: Int):String = if (s.length<=k) s
else digitSum(s.chunked(k){it.sumOf{it-'0'}}.joinToString(""),k)
pub fn digit_sum(mut s: String, k: i32) -> String {
while s.len() > k as _ {
s = s.as_bytes().chunks(k as _).map(|c| c.iter().fold(0, |a, b| a + *b as i32 - 48)).join("")
} s
}
Comments