题目描述:
1.1.14 Write a static method lg() that takes an int value N as argument and returns the largest int not larger than the base-2 logarithm of N. Do not use Math.
注意,不让用 Java 的 Math 类里的方法
Kotlin 实现
fun main(args: Array<String>) {
println(log2(79325))
//使用Math的方法验证结果是否正确
println((Math.log(79325.0) / Math.log(2.0)).toInt())
}
fun log2(n: Int): Int {
when (n) {
0 -> return -1
1 -> return 0
2 -> return 1
}
var track = 2
for (i in 1 until n) {
track *= 2
if (track > n)
return i
}
return 0
}