Skip to content

Instantly share code, notes, and snippets.

@ChrisGuzman
Created April 2, 2020 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisGuzman/eec1c8f6b0c91d3bd70628858c6c8ac8 to your computer and use it in GitHub Desktop.
Save ChrisGuzman/eec1c8f6b0c91d3bd70628858c6c8ac8 to your computer and use it in GitHub Desktop.
LeetCode #2 Happy Number
fun main(args: Array<String>) {
println(isHappy(1111111))
}
fun isHappy(n: Int): Boolean {
val mathed = doTheMath(n)
println(mathed)
return mathed == 1
}
fun doTheMath(myNum: Int): Int {
var mutableParam = myNum
val digits = ArrayList<Int>()
while (mutableParam > 0) {
digits.add(mutableParam % 10)
mutableParam /= 10
}
println(digits)
val summed = digits.map { it * it }.sum()
println(summed)
return if (summed.length() > 1) {
doTheMath(summed)
} else {
summed
}
}
fun Int.length() = when(this) {
0 -> 1
else -> Math.log10(Math.abs(toDouble())).toInt() + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment