Swift算法3-power of 2

Given an integer, write a function to determine if it is a power of two.
四种方法:(可以看一下迭代和递归的区别)

  1. 迭代 O(log n):
class Solution {
    func isPowerOfTwo(var n: Int) -> Bool {
    if (n == 0) {
        return false
    } else {
        while (n % 2 == 0) {
            n /= 2
        }
    }
    return (n == 1)
    }
}
  1. 递归 O(log n):
class Solution2 {
    func isPowerOfTwo1(var n: Int) -> Bool {
        return n > 0 && (n == 1 || (n % 2 == 0 && isPowerOfTwo1(n / 2)))
    }
}

3.bit O(1):
因为2的n次方的二进制表示法 & 2的n次方-1的二进制表示法 的值为0

class Solution {
    func isPowerOfTwo(n: Int) -> Bool {
    return n > 0 && (n & (n - 1) == 0)
    }
}
  1. Math O(1):
    Because the range of an integer = -2147483648 (-2^31) ~ 2147483647 (2^31-1), the max possible power of two = 2^30 = 1073741824.

(1) If n is the power of two, let n = 2^k, where k is an integer.

We have 2^30 = (2^k) * 2^(30-k), which means (2^30 % 2^k) == 0.

(2) If n is not the power of two, let n = j*(2^k), where k is an integer and j is an odd number.

We have (2^30 % j*(2^k)) == (2^(30-k) % j) != 0.

class Solution {
    func isPowerOfTwo(n: Int) -> Bool {
    return n > 0 && (1073741824 % n == 0)
    }
}

But is the last solution do-able?
I don't like the last solution!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 选取天天果园 PC Banner分析: 目的:以猕猴桃为主要对象,吸引用户点击,浏览,直至商品交易环节; 对象:对...
    张文武贝阅读 351评论 0 0
  • 学习来源:CNTV➕网资 学习时段:大三上学年 今天我们将一起走进数落在民间的,却经历了千百年历史文化变迁的古老城...
    信香阅读 245评论 0 1
  • 昨天一天在两处看到了有关麦当劳的记忆。 先是豆瓣上看到作家米周写了麦当劳在小时候的记忆里简直是一种高贵的食物,几乎...
    小山羊的二三言阅读 613评论 0 0

友情链接更多精彩内容