Sunday, September 17, 2017

231. Power of Two

Given an integer, write a function to determine if it is a power of two.

Solution, there are couple ways to do it.
Iteration, recursion, keep check if the number can divided by two until it reach to 1.

I am not going to post these two methods.

Some advanced method:
use n & (n-1) trick, basically the bit form of any number that is power of 2 is 1 plus couple of 0, while n-1 is 0 plus same amount of 1, so n& (n-1) would be 0.


The other method is since 2 is a prime number, so any power of 2 should be the factor of 2^30 (largest integer 1073741824 that is power of 2 ). So we can use 1073741824 mod n to check if n is power of 2.


 public boolean isPowerOfTwo(int n) {  
     if(n<=0) return false;  
     return (n & (n-1)) ==0;  
   }  
 public boolean isPowerOfTwo(int n) {  
     if(n<=0) return false;  
     return 1073741824%n ==0;  
   }  

No comments:

Post a Comment