题目

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example 1:

  1. Input: 16
  2. Output: true

Example 2:

  1. Input: 5
  2. Output: false

Follow up: Could you solve it without loops/recursion?


题意

判断一个数是不是4的幂次方。

思路

  1. 循环判断余数;
  2. 直接求对数再进行判断;
  3. 找规律:
    首先,0342. Power of Four (E) - 图1相当于将0342. Power of Four (E) - 图2的二进制向左移动两位,初始从1开始,所以4的幂次方的二进制表示中一定只有一个1;
    其次,因为每次向左移动两位,这个1后面一定跟着偶数个0,1一定出现在从右向左第奇数个位置上,只要将num和0342. Power of Four (E) - 图3相与,只要结果不为0,那么这个1一定出现在奇数为上。

代码实现

Java

循环

  1. class Solution {
  2. public boolean isPowerOfFour(int num) {
  3. while (num > 1) {
  4. if (num % 4 != 0) {
  5. return false;
  6. }
  7. num /= 4;
  8. }
  9. return num == 1;
  10. }
  11. }

对数

  1. class Solution {
  2. public boolean isPowerOfFour(int num) {
  3. double n = Math.log(num) / Math.log(4);
  4. return n == ((int) n) * 1.0;
  5. }
  6. }

找规律

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