java.lang.Object
g2201_2300.s2243_calculate_digit_sum_of_a_string.Solution

public class Solution extends Object
2243 - Calculate Digit Sum of a String.<p>Easy</p> <p>You are given a string <code>s</code> consisting of digits and an integer <code>k</code>.</p> <p>A <strong>round</strong> can be completed if the length of <code>s</code> is greater than <code>k</code>. In one round, do the following:</p> <ol> <li><strong>Divide</strong> <code>s</code> into <strong>consecutive groups</strong> of size <code>k</code> such that the first <code>k</code> characters are in the first group, the next <code>k</code> characters are in the second group, and so on. <strong>Note</strong> that the size of the last group can be smaller than <code>k</code>.</li> <li><strong>Replace</strong> each group of <code>s</code> with a string representing the sum of all its digits. For example, <code>&quot;346&quot;</code> is replaced with <code>&quot;13&quot;</code> because <code>3 + 4 + 6 = 13</code>.</li> <li><strong>Merge</strong> consecutive groups together to form a new string. If the length of the string is greater than <code>k</code>, repeat from step <code>1</code>.</li> </ol> <p>Return <code>s</code> <em>after all rounds have been completed</em>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s = &ldquo;11111222223&rdquo;, k = 3</p> <p><strong>Output:</strong> &ldquo;135&rdquo;</p> <p><strong>Explanation:</strong></p> <ul> <li>For the first round, we divide s into groups of size 3: &ldquo;111&rdquo;, &ldquo;112&rdquo;, &ldquo;222&rdquo;, and &ldquo;23&rdquo;.</li> </ul> <p>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.</p> <p>So, s becomes &ldquo;3&rdquo; + &ldquo;4&rdquo; + &ldquo;6&rdquo; + &ldquo;5&rdquo; = &ldquo;3465&rdquo; after the first round.</p> <ul> <li>For the second round, we divide s into &ldquo;346&rdquo; and &ldquo;5&rdquo;.</li> </ul> <p>Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5.</p> <p>So, s becomes &ldquo;13&rdquo; + &ldquo;5&rdquo; = &ldquo;135&rdquo; after second round.</p> <p>Now, s.length <= k, so we return &ldquo;135&rdquo; as the answer.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s = &ldquo;00000000&rdquo;, k = 3</p> <p><strong>Output:</strong> &ldquo;000&rdquo;</p> <p><strong>Explanation:</strong></p> <p>We divide s into &ldquo;000&rdquo;, &ldquo;000&rdquo;, and &ldquo;00&rdquo;.</p> <p>Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0.</p> <p>s becomes &ldquo;0&rdquo; + &ldquo;0&rdquo; + &ldquo;0&rdquo; = &ldquo;000&rdquo;, whose length is equal to k, so we return &ldquo;000&rdquo;.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= s.length <= 100</code></li> <li><code>2 <= k <= 100</code></li> <li><code>s</code> consists of digits only.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details