93.3k views
15 votes
Write a java program to input a number from the user and tell if that number is a power of 2 or not.

Powers of 2 are 1, 2, 4, 8, 16, 32, 64, 128, 256 and so on.

User Jarod
by
5.7k points

1 Answer

10 votes

Answer:

public static boolean isPowerOfTwo(int n) {

long exp = Math.round(Math.log(n) / Math.log(2));

return Math.pow(2, exp) == n;

}

Step-by-step explanation:

The opposite of power-of-2 is the 2-log, which is calculated using any log divided by log(2).

I'm sure you can do the input part yourself!

User Jayant Bhawal
by
5.1k points