Skip to content

Instantly share code, notes, and snippets.

@pchrysa
Created August 2, 2017 21:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pchrysa/fe97f32e7da7117ed768b0964e580a97 to your computer and use it in GitHub Desktop.
Save pchrysa/fe97f32e7da7117ed768b0964e580a97 to your computer and use it in GitHub Desktop.
Sum digits of a given number in Kotlin
/*
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())
}
@MartinNiederl
Copy link

You could also use the sumBy() function like: val sum: Int = input.sumBy { it - '0' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment