LeetCode - Easy - 342. Power of Four

悠悠 2022-12-27 06:25 248阅读 0赞

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:

  1. Input: n = 16
  2. Output: true

Example 2:

  1. Input: n = 5
  2. Output: false

Example 3:

  1. Input: n = 1
  2. Output: true

Constraints:

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

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

Analysis

方法1:数学除余


方法2:位运算

对于一个整数而言,如果这个数是 4 的幂次方,那它必定也是 2 的幂次方。


















































十进制 二进制
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 位)

从上表看出,是4的幂次方的数二进制形式中的1在奇数位。

于是,检测值与一个特殊的数做 & 位运算,用来判断检测值的二进制形式中的1是否在奇数位。

这个特殊的数有如下特点:

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

符合这两个条件的二进制数是1010101010101010101010101010101,转换成0x55555555

Submission

  1. public class PowerOfFour {
  2. //方法2:
  3. public boolean isPowerOfFour(int num) {
  4. return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0;
  5. // 0x55555555 is to get rid of those power of 2 but not power of 4
  6. // so that the single 1 bit always appears at the odd position
  7. }
  8. //方法1:
  9. public boolean isPowerOfFour2(int num) {
  10. while ((num != 0) && (num % 4 == 0)) {
  11. num /= 4;
  12. }
  13. return num == 1;
  14. }
  15. }

Test

  1. public class PowerOfFourTest {
  2. @Test
  3. public void test() {
  4. PowerOfFour pf = new PowerOfFour();
  5. assertTrue(pf.isPowerOfFour(4));
  6. assertTrue(pf.isPowerOfFour(16));
  7. assertFalse(pf.isPowerOfFour(17));
  8. assertFalse(pf.isPowerOfFour(5));
  9. }
  10. @Test
  11. public void test2() {
  12. PowerOfFour pf = new PowerOfFour();
  13. assertTrue(pf.isPowerOfFour2(4));
  14. assertTrue(pf.isPowerOfFour2(16));
  15. assertFalse(pf.isPowerOfFour2(17));
  16. assertFalse(pf.isPowerOfFour2(5));
  17. }
  18. }

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读