LeetCode 231 [Power of Two]

作者: Jason_Yuan | 来源:发表于2016-08-02 13:00 被阅读9次

原题

用 O(1) 时间检测整数 n 是否是 2 的幂次。

样例
n=4,返回 true;
n=5,返回 false.

解题思路

  • 本题考查bit操作
  • 数学问题,照例先观察前几项
1 => 1 
2 => 10
4 => 100
8 => 1000
16 => 10000
...
  • 可以发现,2的次方数与2的次方数减1的相与一定为零

完整代码

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and n & (n - 1) == 0

相关文章

网友评论

    本文标题:LeetCode 231 [Power of Two]

    本文链接:https://www.haomeiwen.com/subject/akvfsttx.html