Skip to content

Instantly share code, notes, and snippets.

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