Sunday, 17 July 2016

Power of 2

/*  Given an integer, write a function to determine if it is a power of two. */
/*
    Approach 1: Using right shift in O(n)
    Approach 2: N(of the form 2^k) has only one 1 in msb and all 1's and (N - 1) has only one 0 in msb and all 1's so the and of the two will be 0 if N is a power of 2. O(1) solution
*/


 #include <iostream>  
 #include <cmath>  
 using namespace std;  
 bool isPowerofTwo(int N){  
   if(N < 1){  
     return false;  
   }  
   while(N > 1){  
     if((N & 1) == 1){  
       return false;  
     }  
     N = N >> 1;  
   }  
   return true;  
 }  
 bool isPowerEfficient(int N){  
   if(N < 0)  
     return false;  
   return N == 1 || !(N & (N - 1));  
 }  
 int main(){  
   int N = 1;  
   //bool isPower = isPowerofTwo(N);  
   bool isPower = isPowerEfficient(N);  
   if(isPower)  
     cout << "YES" << endl;  
   else  
     cout << "NO" << endl;  
   return 0;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive