Leetcode实战:231.2的幂

题目:

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例1:

1
2
3
输入: 1
输出: true
解释: 20 = 1

示例2:

1
2
3
输入: 16
输出: true
解释: 24 = 16

示例3:

1
2
输入: 218
输出: false

算法实现:

如果n时2的幂 n & (n - 1) == 0

1
2
3
4
5
6
7
class 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的幂/
Author
chenxindaaa
Posted on
October 4, 2019
Licensed under