Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created January 6, 2013 11:00
Show Gist options
  • Save ozkansari/4466580 to your computer and use it in GitHub Desktop.
Save ozkansari/4466580 to your computer and use it in GitHub Desktop.
Checking if a number can be written as power of 2 using bitwise operations
/**
* Problem: Given an integer, i, find whether it can be expressed as 2^k. Where k< i
*/
class PowerOf2Util2 {
/**
* 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(1)
* Space complexity : 0(1)
*/
private static boolean isPowerOf2Number(int input){
if(input==0) return false;
if(input<0) input=-1*input;
int result = input&(input-1);
return result==0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment