来源

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

描述

给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
示例 1:
输入: 16
输出: true

示例 2:
输入: 5
输出: false

进阶:
你能不使用循环或者递归来完成本题吗?

题解

数学运算

  1. class Solution {
  2. public boolean isPowerOfFour(int num) {
  3. return (num > 0) && ((Math.log(num) / Math.log(2)) % 2 == 0);
  4. }
  5. }

位运算

  1. class Solution {
  2. public boolean isPowerOfFour(int num) {
  3. return (num > 0) && ((num & num - 1) == 0) && ((num & 0xaaaaaaaa) == 0);
  4. }
  5. }

位运算 + 数学运算

  1. class Solution {
  2. public boolean isPowerOfFour(int num) {
  3. return (num > 0) && ((num & (num - 1)) == 0) && (num % 3 == 1);
  4. }
  5. }

复杂度分析

  • 时间复杂度:342. 4的幂(Power of Four) - 图1
  • 空间复杂度:342. 4的幂(Power of Four) - 图2