算法4练习题(Kotlin)-1.1.14 以2为底的log()

题目描述:
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
}

运行结果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 春天一场雨, 田地万千及。 渺渺云烟起, 浓浓春雨驰。 禾苗添绿态, 山色显青姿。 久旱降甘霖, 人思洗世期。
    李缓之阅读 1,522评论 52 50
  • 不要去过份地苛求,不要有太多的奢望,既然上帝要熬炼于我,不让自己鹤立鸡群,不让自己出类拔萃,又何必硬要去强求呢?金...
    蒙恩的人_bfbe阅读 791评论 0 1
  • 在准备《不讲就出局》第一篇作业时,我想到《为你读诗》这款APP当中的一首诗歌《旅程》,特别喜欢作家奥立费写...
    雪茵聊教育阅读 1,052评论 0 0
  • 文|向璐 1 人们都说:色字头上一把刀。其实,何止是“色”字呢? 人的欲望是无止境的,不懂得自我克制,便会愈演愈烈...
    向璐LousanHeung阅读 644评论 0 9