Leetcode实战:231.2的幂
题目:
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例1:
1 | |
示例2:
1 | |
示例3:
1 | |
算法实现:
如果n时2的幂 n & (n - 1) == 0 1
2
3
4
5
6
7class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n & (n - 1) == 0 if n != 0 else 0
结果:
Leetcode实战:231.2的幂
http://chenxindaaa.com/Programming/Leetcode/Leetcode/Leetcode实战:231.2的幂/