2243. Calculate Digit Sum of a String

Difficulty:
Related Topics:
Similar Questions:

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:

Return s after all rounds have been completed.

  Example 1:

Input: s = "11111222223", k = 3
Output: "135"
Explanation: 
- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".
  ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. 
  So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round.
- For the second round, we divide s into "346" and "5".
  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. 
  So, s becomes "13" + "5" = "135" after second round. 
Now, s.length <= k, so we return "135" as the answer.

Example 2:

Input: s = "00000000", k = 3
Output: "000"
Explanation: 
We divide s into "000", "000", and "00".
Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. 
s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".

  Constraints:

Solution (Java)

class Solution {
    public String digitSum(String s, int k) {
        while (s.length() > k) {
            int n = s.length();
            int count = 0;
            int sum = 0;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++) {
                if (count == k) {
                    sb.append(sum);
                    sum = 0;
                    count = 0;
                }
                sum += s.charAt(i) - '0';
                count++;
            }
            sb.append(sum);
            s = sb.toString();
        }
        return s;
    }
}

Explain:

nope.

Complexity: