231. Power of Two
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.
Subscribe to see which companies asked this question
根据提示是用位运算,所以我就采用了python中的位运算
- class Solution(object):
- def isPowerOfTwo(self, n):
- """
- :type n: int
- :rtype: bool
- """
- if n<=0:
- return False
- a = bin(n).replace('0b','')
- if a.count('1') == 1:
- return True
- return False
遇到的问题有两个:一个是对Python的自带函数不是很熟,需要查资料才做出来。
另外一个是,一开始的思路是打算用math.log函数计算,因为python的精度没有处理好。所以放弃。不得不说,python的精度还是麻烦