[刷题防痴呆] 0342 - 4的幂 (Power of Fou
2021-11-01 本文已影响0人
西出玉门东望长安
题目地址
https://leetcode.com/problems/power-of-four/description/
题目描述
342. Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
思路
- 递归可求解.
- 位运算也可求解.
关键点
- 递归不停除4, 看最后等不等于1.
代码
- 语言支持:Java
// 递归
class Solution {
public boolean isPowerOfFour(int num) {
if (num < 1) {
return false;
}
while (num % 4 == 0) {
num /= 4;
}
return num == 1;
}
}
// 位运算
class Solution {
public boolean isPowerOfFour(int n) {
return n > 0 && (n & (n - 1)) == 0 && n % 3 == 1;
}
}