Created
April 2, 2020 21:59
-
-
Save ChrisGuzman/eec1c8f6b0c91d3bd70628858c6c8ac8 to your computer and use it in GitHub Desktop.
LeetCode #2 Happy Number
This file contains 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
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