LeetCode 231. Power of Two

题目

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

Example 1:

1
2
3
Input: 1
Output: true
Explanation: 20 = 1

Example 2:

1
2
3
Input: 16
Output: true
Explanation: 24 = 16

Example 3:

1
2
Input: 218
Output: false

思路

记住2的x幂次的特点:

  • 表示成二进制一定是一个1后面若干个0,即bin(n).count('1') == 1
  • 那么n-1一定是一个0后面若干个1,即n & (n-1) == 0

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# class Solution(object):
# def isPowerOfTwo(self, n):
# """
# :type n: int
# :rtype: bool
# """
# return n > 0 and bin(n).count('1') == 1


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