1. 程式人生 > 其它 >LeetCode - Easy - 342. Power of Four

LeetCode - Easy - 342. Power of Four

技術標籤:演算法與資料結構LeetCodeleetcode位運算

Topic

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

方法1:數學除餘


方法2:位運算

對於一個整數而言,如果這個數是 4 的冪次方,那它必定也是 2 的冪次方。

十進位制二進位制
210
4100 (1 在第 3 位)
81000
1610000(1 在第 5 位)
32100000
641000000(1 在第 7 位)
12810000000
256100000000(1 在第 9 位)
5121000000000
102410000000000(1 在第 11 位)

從上表看出,是4的冪次方的數二進位制形式中的1在奇數位。

於是,檢測值與一個特殊的數做 & 位運算,用來判斷檢測值的二進位制形式中的1是否在奇數位。

這個特殊的數有如下特點:

  • 足夠大,但不能超過 32 位,即最大為 31 個 1
  • 它的二進位制表示中奇數位為 1 ,偶數位為 0

符合這兩個條件的二進位制數是1010101010101010101010101010101,轉換成0x55555555

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));
	}
}