w3resource

Kotlin recursive function: Sum of digits in a string


Write a Kotlin recursive function to calculate the sum of all digits in a string.


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should understand these concepts:

  • Recursion: A function calling itself with modified input until a base condition is met.
  • String Manipulation: Extracting characters from a string and modifying substrings.
  • Character Checking: Identifying whether a character is a digit using isDigit().
  • Base Case: Stopping recursion when the string is empty.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: The base case should return 0 when the string is empty.
  • Hint 2: Use isDigit() to check if a character is a number.
  • Hint 3: Convert a digit character to an integer using Character.getNumericValue().
  • Hint 4: Use recursion to process the remaining part of the string after extracting the first character.
  • Hint 5: If the first character is not a digit, simply continue with the rest of the string.

Sample Solution:

Kotlin Code:

fun sumOfDigits(str: String): Int {
    if (str.isEmpty()) {
        return 0
    }

    val firstChar = str[0]
    val isDigit = firstChar.isDigit()

    return if (isDigit) {
        val digitValue = Character.getNumericValue(firstChar)
        digitValue + sumOfDigits(str.substring(1))
    } else {
        sumOfDigits(str.substring(1))
    }
}

fun main() {
    val input = "abc123def45gh6"
    val sum = sumOfDigits(input)
    println("Sum of digits in '$input' is: $sum")
}

Sample Output:

Sum of digits in 'abc123def45gh6' is: 21

Explanation:

In the above exercise –

The "sumOfDigits()" function takes a string str as an argument and recursively calculates the sum of all the digits in the string.

The function follows these steps:

  • As long as str is empty, the recursion will end, and the function will return 0 to indicate the recursion has ended.
  • Otherwise, it checks if the first character 'firstChar' of the string is a digit using the isDigit function.
  • If 'firstChar' is a digit, it converts it to an integer using Character.getNumericValue() and adds it to the sum of the remaining digits in the substring obtained by removing the first character (str.substring(1)).
  • If 'firstChar' is not a digit, it skips it and calculates the sum of the remaining digits in the substring (str.substring(1)).
  • The recursive call continues until the string is empty, and the final sum is returned.

In the "main()" function, we define an input string that contains a mix of letters and digits. We call the "sumOfDigits()" function with this input and store the result in the 'sum' variable. Finally, we print the sum to the console.

Kotlin Editor:


Previous: Check prime number.
Next: Sum of even Fibonacci numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.