来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-four/
描述
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
示例 1:
输入: 16
输出: true
示例 2:
输入: 5
输出: false
题解
数学运算
class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ((Math.log(num) / Math.log(2)) % 2 == 0);
}
}
位运算
class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ((num & num - 1) == 0) && ((num & 0xaaaaaaaa) == 0);
}
}
位运算 + 数学运算
class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && (num % 3 == 1);
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度: