Westonci.ca is the premier destination for reliable answers to your questions, brought to you by a community of experts. Get immediate and reliable answers to your questions from a community of experienced professionals on our platform. Our platform provides a seamless experience for finding reliable answers from a network 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 :

tonb

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!