Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created January 6, 2013 11:05
Show Gist options
  • Save ozkansari/4466609 to your computer and use it in GitHub Desktop.
Save ozkansari/4466609 to your computer and use it in GitHub Desktop.
Checking if a number can be written as kth power of 2 using bitwise operations
/**
* Problem: Given an integer, i, find whether it can be expressed as 2^k. Where k< i
*/
class PowerOf2Util4 {
/**
* Test
*/
public static void main(String[] args) {
int k=18;
int input = 262144; // 2^18
System.out.print( input + " is " + k + "th power of 2 ? " );
System.out.println( isKthPowerOf2Number(input,k) );
}
/**
* Time complexity: O(1)
* Space complexity : 0(1)
*/
private static boolean isKthPowerOf2Number(int input, int k){
return ( (1<<k) == input) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment