Sunday, October 15, 2017

342. Power of Four

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?

Solution:
First of all, power of 4 should be also power of 2, The only difference is 
1. Power of 4 is a perfect square number while power of 2 is not.
 public boolean isPowerOfFour(int num) {  
     int a=(int)Math.sqrt(num);  
     return (num>0 && (num&(num-1))==0 && a*a==num );   
   }  

2. (Power of 4 -1) can be divided by 3 while power of 2 cannot.
 public boolean isPowerOfFour(int num) {  
     return (num>0 && (num&(num-1))==0 && (num-1)%3==0 );   
   }  

No comments:

Post a Comment