Created
January 6, 2013 11:05
-
-
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
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 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