题目
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?
链接
https://leetcode.com/problems/power-of-four/?tab=Description
3/8/2017
没有想到follow up的方法
1 public class Solution { 2 public boolean isPowerOfFour(int num) { 3 if (num <= 0) return false; 4 while (num != 1) { 5 if (num % 4 != 0) return false; 6 num /= 4; 7 } 8 return true; 9 } 10 }
他人的好算法
1 public boolean isPowerOfFour(int num) { 2 return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0; 3 //0x55555555 is to get rid of those power of 2 but not power of 4 4 //so that the single 1 bit always appears at the odd position 5 }
另外一个,可以用于任何power的例子,只需要把底数改了即可。
1 public boolean isPowerOfFour(int num) { 2 return Integer.toString(num, 4).matches("10*"); 3 }