Get expert advice and community support for all your questions on IDNLearn.com. Ask any question and get a thorough, accurate answer from our community of experienced professionals.

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.


Sagot :

Answer:

 public static boolean isPowerOfTwo(int n) {

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

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

 }

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!