美文网首页
[LeetCode][Python]231. Power of

[LeetCode][Python]231. Power of

作者: bluescorpio | 来源:发表于2017-06-25 22:49 被阅读62次

Given an integer, write a function to determine if it is a power of two.

解题思路:

看起来很简单的一道题,竟然一开始没有任何思路。不过看了提示还是自己又忘记了n&(n-1)。(n&(n-1))==0的含义,n的最高有效位为1,其余位为0。因此,n的值是2的某次方。所以,(n&(n-1))==0检查n是否为2的某次方(或者检查n是否为0)

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return (n>0 and n&(n-1)==0)

相关文章

网友评论

      本文标题:[LeetCode][Python]231. Power of

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