231. Power of Two
2016-05-11 本文已影响6人
codingXue
问题描述
Given an integer, write a function to determine if it is a power of two.
Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路分析
- 用log函数,判断得到的指数是否约为整数。Runtime: 76 ms, which beats 5.28% of Python submissions.
- 循换进行模2判断并右移一位。Runtime: 68 ms, which beats 13.69% of Python submissions.
- 将十进制数转为二进制字符串,除第一位外其他位均为0则该数字是2的幂。Runtime: 56 ms, which beats 67.47% of Python submissions.
AC代码
class Solution(object):
def isPowerOfTwo(self, n):
if n <= 0:
return False
return n == 1 or not '1' in bin(n)[3:]