231. Power of Two

来源:互联网 发布:金麦汽修软件 编辑:程序博客网 时间:2024/05/16 01:11

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

题意:给一个整数,写一个函数判读它是不是2的幂

思路1:可以直接除以2,知道余数为0,或者1,余数是0则是2的幂,否则不是

思路2:这里可以用位运算进行解决,如果是2的幂,则其二进制表示一定是‘10000....’,让其与(n-1)二进制为'1111....'求与运算,结果肯定是0,如结果不是0,则其不是2的幂(这里题目中没有说该数为正整数,所以要做一个判断,小于等于0的数都不是2的幂)

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

(这里有个小问题,为什么python用位运算提交代码,运行效率并不高呢?提交多次,运行时间都比大部分人都运行时间要长。)

0 0
原创粉丝点击