leetcode python3 简单题231. Power of Two

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第二百三十一题

(1)题目
英文:
Given an integer, write a function to determine if it is a power of two.

Example 1:

Input: 1
Output: true
Explanation: 20 = 1

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

示例 1:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-two

(2)解法
使用二进制位运算,思路是:2的幂指数对应的二进制除了第一位是1其余都是0,而将这个数减一后,将得到互补的二进制,相与就得0
(耗时:48ms,内存:13.8M)

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

猜你喜欢

转载自blog.csdn.net/qq_37285386/article/details/106108223