0
Checking wether a number can be written as power of 2
What is the most efficient way to check weather a given number can be written as power of 2 or not ? If possible please give the program approach in C or Java Ex: 4 â> true 16 â> true 20 â> false 256 â> true
3 Answers
+ 4
public class Program
{
public static void main(String[] args) {
int num = 534;
int pow2 = 1;
while(pow2<num){
pow2 *= 2;
}
System.out.println(pow2==num) ;
}
}
+ 1
Find log to base 2. Must be an integer.
Convert to binary.Must have exactly one 1.
0
Written as power of two or verified as power of two?