Welcome to Westonci.ca, where you can find answers to all your questions from a community of experienced professionals. Experience the ease of finding accurate answers to your questions from a knowledgeable community of professionals. Get detailed and accurate answers to your questions from a dedicated community of experts on our Q&A platform.

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!

We hope you found this helpful. Feel free to come back anytime for more accurate answers and updated information. We hope our answers were useful. Return anytime for more information and answers to any other questions you have. We're glad you visited Westonci.ca. Return anytime for updated answers from our knowledgeable team.