[LeetCode] Calculate Digit Sum of a String

2243. Calculate Digit Sum of a String

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:

  1. 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.
  2. 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.
  3. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int parse(string& s, int &p, int k) {
int ed = p + k, res = 0;
while(p < s.length() and p < ed) {
res = res + (s[p++] & 0b1111);
}
return res;
}
public:
string digitSum(string s, int k) {
while(s.length() > k) {
int i = 0;
string ns = "";
while(i < s.length())
ns += to_string(parse(s, i, k));
s = ns;
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/17/PS/LeetCode/calculate-digit-sum-of-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.