Created
August 2, 2017 21:29
-
-
Save pchrysa/fe97f32e7da7117ed768b0964e580a97 to your computer and use it in GitHub Desktop.
Sum digits of a given number in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
In mathematics, the digit sum of a given integer is the sum of all its digits (e.g. | |
the digit sum of 84001 is calculated as 8+4+0+0+1 = 13). | |
Write a function that will get an integer and will return the digit sum for that integer. | |
*/ | |
fun main(args: Array<String>) { | |
sumOfDigits("84001"); | |
} | |
fun sumOfDigits(n: String) { | |
val arr = n.toList() | |
val arrOfInt = arr.map{ it.toString().toInt() } | |
print(arrOfInt.sum()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could also use the
sumBy()
function like:val sum: Int = input.sumBy { it - '0' }