w3resource

Kotlin recursive function: Sum of digits in a string

Kotlin Function: Exercise-9 with Solution

Write a Kotlin recursive function to calculate the sum of all digits in a 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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-9.php