美文网首页
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

相关文章

  • 一起学算法-231. 2 的幂

    一、题目 LeetCode-231. 2 的幂链接:https://leetcode-cn.com/problem...

  • LeetCode 231-240

    231. 2的幂[https://leetcode-cn.com/problems/power-of-two/] ...

  • Leecode 位运算

    231. 2的幂[https://leetcode-cn.com/problems/power-of-two/] ...

  • Leetcode 231 2的幂

    题目 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1: 输入: 1输出: true解释: 20...

  • (n&n-1)==0是不是2的幂次

    leetcode231. 2的幂 “给定一个整数,编写一个函数来判断它是否是 2 的幂次方。” 有大神用一行代码搞...

  • [LeetCode]231-2的幂

    231. 2的幂给定一个整数,编写一个函数来判断它是否是 2 的幂次方。示例:输入: 1 -> 输出: true输...

  • Leetcode 231. 2的幂

    题目描述 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1: 输入: 1输出: true解释: ...

  • leetcode 231 python 2的幂

    传送门 题目要求 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1:输入: 1输出: true解...

  • LeetCode-231 2的幂

    题目 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1: 示例 2: 示例 3: 我的AC 版本...

  • leetcode 231. 2的幂

    leetcode[https://leetcode-cn.com/problems/power-of-two/] ...

网友评论

      本文标题:Leetcode 231 2的幂

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