# LeetCode - Easy - 342. Power of Four

2020-12-08 12:23:29 巨輪

# LeetCode - Easy - 342. Power of Four

Bit Manipulation

## Description

https://leetcode.com/problems/power-of-four/

Given an integer `n`, return `true` if it is a power of four. Otherwise, return `false`.

An integer `n` is a power of four, if there exists an integer `x` such that `n == 4^x`.

Example 1:

``````Input: n = 16
Output: true
``````

Example 2:

``````Input: n = 5
Output: false
``````

Example 3:

``````Input: n = 1
Output: true
``````

Constraints:

• -2³¹ <= n <= 2³¹ - 1

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

## Analysis

2 10
4 100 （1 在第 3 位）
8 1000
16 10000（1 在第 5 位）
32 100000
64 1000000（1 在第 7 位）
128 10000000
256 100000000（1 在第 9 位）
512 1000000000
1024 10000000000（1 在第 11 位）

• 足够大，但不能超过 32 位，即最大为 31 个 1
• 它的二进制表示中奇数位为 1 ，偶数位为 0

## Submission

``````public class PowerOfFour {
//方法2：
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0;
// 0x55555555 is to get rid of those power of 2 but not power of 4
// so that the single 1 bit always appears at the odd position
}

//方法1：
public boolean isPowerOfFour2(int num) {
while ((num != 0) && (num % 4 == 0)) {
num /= 4;
}
return num == 1;
}
}
``````

## Test

``````public class PowerOfFourTest {

@Test
public void test() {
PowerOfFour pf = new PowerOfFour();

assertTrue(pf.isPowerOfFour(4));
assertTrue(pf.isPowerOfFour(16));
assertFalse(pf.isPowerOfFour(17));
assertFalse(pf.isPowerOfFour(5));
}

@Test
public void test2() {
PowerOfFour pf = new PowerOfFour();

assertTrue(pf.isPowerOfFour2(4));
assertTrue(pf.isPowerOfFour2(16));
assertFalse(pf.isPowerOfFour2(17));
assertFalse(pf.isPowerOfFour2(5));
}
}
``````

https://my.oschina.net/jallenkwong/blog/4780878