Get comprehensive answers to your questions with the help of IDNLearn.com's community. Ask your questions and get detailed, reliable answers from our community of experienced experts.

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!

Thank you for joining our conversation. Don't hesitate to return anytime to find answers to your questions. Let's continue sharing knowledge and experiences! Your search for answers ends at IDNLearn.com. Thank you for visiting, and we hope to assist you again soon.