Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6e18ef5

Browse files
ybian19azl397985856
authored andcommitted
feat: 342.power-of-four add Python3 implementation (azl397985856#144)
1 parent 2eef0e1 commit 6e18ef5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

‎problems/342.power-of-four.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,13 @@ return num > 0 && num & (num - 1 === 0) && (num - 1) % 3 === 0;
8080
- 数论
8181
- 2的幂次方特点(数学性质以及二进制表示)
8282
- 4的幂次方特点(数学性质以及二进制表示)
83+
8384
## 代码
8485

86+
语言支持:JS, Python
87+
88+
JavaScript Code:
89+
8590
```js
8691
/*
8792
* @lc app=leetcode id=342 lang=javascript
@@ -103,3 +108,24 @@ var isPowerOfFour = function(num) {
103108
return (num & 0x55555555) === num;
104109
};
105110
```
111+
112+
Python Code:
113+
114+
```python
115+
class Solution:
116+
def isPowerOfFour(self, num: int) -> bool:
117+
if num == 1:
118+
return True
119+
elif num < 4:
120+
return False
121+
else:
122+
if not num & (num-1) == 0:
123+
return False
124+
else:
125+
return num & 0x55555555 == num
126+
127+
# 另一种解法:将数字转化为二进制表示的字符串,利用字符串的相关操作进行判断
128+
def isPowerOfFour(self, num: int) -> bool:
129+
binary_num = bin(num)[2:]
130+
return binary_num.strip('0') == '1' and len(binary_num) % 2 == 1
131+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /