Last active
December 10, 2015 17:18
-
-
Save ozkansari/4466560 to your computer and use it in GitHub Desktop.
Checking if a number can be written as power of 2 using bitwise operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Problem: Given an integer, i, find whether it can be expressed as 2^k. Where k< i | |
*/ | |
class PowerOf2Util1 { | |
/** | |
* Test | |
*/ | |
public static void main(String[] args) { | |
int input = 262144; // 2^18 | |
System.out.print( input + " can be written as power of 2 ? " ); | |
System.out.println( isPowerOf2Number(input) ); | |
} | |
/** | |
* Time complexity: O(32)=O(1) or O(logn) ? | |
* Space complexity : 0(1) | |
*/ | |
private static boolean isPowerOf2Number(int input){ | |
if(input==0) return false; | |
if(input<0) input=-1*input; | |
int temp = 1; | |
for (int i=0;i<=32;i++) { | |
if (temp==input) { | |
return true; | |
} | |
temp= temp<<1; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment