Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Relation Problem Power of Two
对于 Power of Two 来说: 通过观察可知: 为2的n次幂的数 其二进制表示只有1位的数为1. 因此可以利用 n & n - 1 是否为零进行判断。 n & n - 1 会去掉 n 二进制表示的最低位的1.
对于Power of Four : 满足Power of Four 的数必定满足Power of Two 如何去掉 多余的那一部分, 通过观察可知 只有是 Power of Four 的数 才满足 n & n - 1 == 0 && (n - 1) % 3 == 0.
1 public class Solution { 2 public boolean isPowerOfFour(int num) { 3 if (num <= 0) { 4 return false; 5 } 6 if (num == 1) { 7 return true; 8 } 9 if ((num & num - 1) == 0 && ((num - 1) % 3 == 0)) { 10 return true; 11 } 12 return false; 13 } 14 }
时间: 2024-10-18 00:16:20