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.

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:

  • 1 <= s.length <= 100
  • 2 <= k <= 100
  • s consists of digits only.

Note: This problem is from LeetCode.
❌ Compiled
❌ Executed
❌ Correct
program main
    implicit none

    character(len=100) :: s
    integer :: k
    integer :: i

    ! Example 1
    s = "11111222223 "
    k = 3
    call solve(s, k)
    print *, s

    ! Example 2
    s = "00000000 "
    k = 3
    call solve(s, k)
    print *, s

contains

subroutine solve(s, k)
    implicit none
    character(len=*), intent(inout) :: s
    integer, intent(in) :: k
    integer :: n
    integer :: i
    integer :: j
    integer :: carry

    n = len_trim(s)
    do while (n > k)
        ! Divide s into consecutive groups of size k
        i = 1
        j = k
        do while (j <= n)
            ! Replace each group of s with a string representing the sum of all its digits
            carry = 0
            do while (i <= j)
                carry = carry + ichar(s(i:i)) - ichar('0')
                i = i + 1
            end do
            write (s(j:j), '(I1)') carry
            j = j + 1
        end do

        ! Merge consecutive groups together to form a new string
        s = merge(s(1:j-1), s(j:))
        n = len_trim(s)
    end do
end subroutine solve

end program main
βœ… Compiled
❌ Executed
❌ Correct
program main
    implicit none
    character(len=100) :: s
    integer :: k, i, j, sum
    character(len=100) :: result

    ! Read input
    read (*, *) s
    read (*, *) k

    ! Initialize result
    result = ""

    ! Loop until the length of the result is less than or equal to k
    do while (len_trim(result) > k)
        ! Divide s into consecutive groups of size k
        sum = 0
        do i = 1, len_trim(s), k
            ! Calculate the sum of the digits in the current group
            do j = i, i + k - 1
                sum = sum + ichar(s(j:j)) - ichar("0")
            end do

            ! Add the sum to the result
            result = trim(result) // char(sum + ichar("0"))
        end do

        ! Replace each group of s with a string representing the sum of its digits
        s = result

        ! Merge consecutive groups together to form a new string
        result = ""
        do i = 1, len_trim(s), k
            result = trim(result) // s(i:i + k - 1)
        end do
    end do

    ! Output result
    write (*, *) result
end program main
🌐 Data from online sources
def is_a_only_before_b(s: str) -> bool:
    last_index_a = -1
    for i, c in enumerate(s):
        if c == 'a':
            last_index_a = i
        elif c == 'b' and last_index_a > -1:
            return False
    return True

The algorithm iterates through each character in the given string s. It maintains a variable called lastIndexA that keeps track of the last index where the character 'a' is found. If it encounters 'a', it updates lastIndexA with the current index. If it encounters 'b' and lastIndexA is not set to -1 (meaning there was an 'a' before it), the algorithm returns false. If the loop completes without returning false, it means that every 'a' appears before every 'b', so the algorithm returns true.

🌐 Data from online sources
bool isAOnlyBeforeB(const std::string& s) {
    int lastIndexA = -1;
    for (size_t i = 0; i < s.length(); ++i) {
        if (s[i] == 'a') {
            lastIndexA = i;
        } else if (s[i] == 'b' && lastIndexA > -1) {
            return false;
        }
    }
    return true;
}

The algorithm iterates through each character in the given string s. It maintains a variable called lastIndexA that keeps track of the last index where the character 'a' is found. If it encounters 'a', it updates lastIndexA with the current index. If it encounters 'b' and lastIndexA is not set to -1 (meaning there was an 'a' before it), the algorithm returns false. If the loop completes without returning false, it means that every 'a' appears before every 'b', so the algorithm returns true.