美文网首页
Leetcode 231 2的幂

Leetcode 231 2的幂

作者: 禾木清清 | 来源:发表于2019-07-11 19:30 被阅读0次

    题目

    给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

    示例 1:

    输入: 1
    输出: true
    解释: 20 = 1
    示例 2:

    输入: 16
    输出: true
    解释: 24 = 16
    示例 3:

    输入: 218
    输出: false

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/power-of-two
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解决思路一

    一个数如果是2的幂,那么其二进制(n & (n-1)) == 0
    2: 10
    4: 100
    8: 1000
    结果-1以后,所有位都是1.

    代码

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

    解决思路二:

    一直除,直到结果为2。

    class Solution(object):
        def isPowerOfTwo(self, n):
            """
            :type n: int
            :rtype: bool
            """
            if n < 1:
                return False
            
            while n % 2 == 0:
                n = n/2
            
            if n == 1:
                return True
            else:
                return False
    
    

    相关文章

      网友评论

          本文标题:Leetcode 231 2的幂

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