In this post we will talk and learn **How can you check if the given number is power of 2?** using an example.

This can be easily checked using bitwise operators in Java. Firstly, let’s see how a number looks in binary when it is power of two.

From the figure, we can see that only 1 bit is set for all numbers which are exponent of 2.

Let’s now write a method to check if only nth bit of a number is set to true.

public static boolean isPowerOfTwo(int number) {

return (number > 0) && ((number & (number – 1)) == 0);

}

The first condition (number > 0) checks if the number is positive, because the second condition works only for positive numbers.

The second condition ((number & (number – 1)) will return zero for a number which is exponent of two (provided the number is positive). For example, in case of number 32

Thus, through the above code, we are checking if the number is positive and is power of two.

**Let’s write a complete example**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.kkjavatutorials.client; import java.util.Scanner; public class CheckPowerOfTwo { /** * @param KK JavaTutorials * Java program to check if the given number is power of 2? */ public static void main(String[] args) { Scanner scanner = null; int number; try { scanner = new Scanner(System.in); System.out.print("Enter number:"); number = scanner.nextInt(); boolean powerOfTwo = isPowerOfTwo(number); if (powerOfTwo) System.out.println(number + " is power of 2"); else System.out.println(number + " is not power of 2"); } catch (Exception e) { e.printStackTrace(); } } /** * @param number input data * @return returns true if input number is power of 2 else else false */ public static boolean isPowerOfTwo(int number) { return (number > 0) && ((number & (number - 1)) == 0); } } |

**Output of above programs for few inputs::**

1 2 3 4 5 6 7 8 9 10 11 |
Enter number:23 23 is not power of 2 Enter number:8 8 is power of 2 Enter number:264 264 is not power of 2 Enter number:100 100 is not power of 2 |

That’s all about **How can you check if the given number is power of 2?**

If you have any feedback or suggestion please feel free to drop in blow comment box.