Skip to content

2243. Calculate Digit Sum of a String 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  string digitSum(string s, int k) {
    while (s.length() > k) {
      string next;
      for (int i = 0; i < s.length(); ++i)
        next += to_string(accumulate(
            s.begin() + i, s.begin() + min(static_cast<int>(s.length()), i + k),
            0, [](int subtotal, char c) { return subtotal + c - '0'; }));
      s = std::move(next);
    }
    return s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public String digitSum(String s, int k) {
    while (s.length() > k) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < s.length(); i += k) {
        int sum = 0;
        for (int j = i; j < Math.min(s.length(), i + k); ++j)
          sum += s.charAt(j) - '0';
        sb.append(sum);
      }
      s = sb.toString();
    }
    return s;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def digitSum(self, s: str, k: int) -> str:
    while len(s) > k:
      next = []
      for i in range(0, len(s), k):
        summ = 0
        for j in range(i, min(len(s), i + k)):
          summ += int(s[j])
        next.append(str(summ))
      s = ''.join(next)
    return s