Last updated on March 12th, 2017 at 07:08 pm

There are many approaches to check if number is power of two or not.

### Approach 1:

It is very easy and straight forward approach.

- Run a while loop which checks for condition if n is even number (n%2==0).
- If n is even then divide it by 2 in each iteration.
- When you get out of while loop and n is equal to 1 then number is power of two,
- If number is not equal to 1 then number is not power of two.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static boolean powerOfTwoGeneral(int n) { while(n%2==0) { n=n/2; } if(n==1) { return true; } else { return false; } } |

### Approach 2:

We can use bitwise and operator to check if number is power of two or not.

1 2 3 4 5 6 |
public static boolean powerOfTwoBitwise(int n) { return (n & n-1)==0; } |

It will a very simple way to check if number is power of two. Let’s see how it works.

Let’s say n is 8. Its binary representation will be : 1000.

binary represetation of 7 will be : 0111.

1 0 0 0

& 0 1 1 1

———-

0 0 0 0

———-

If number is power of 2, then it will have only one bit set to “1”.

For example:

8 : 1000

32 : 100000

Similarly when you check binary form of 7 and 31, it will have all the bits set to “1”

7 : 111

31: 11111

so if you apply bitwise & operator on n and n-1 and result is 0. It means number is power of two.

### Java program to check if number is power of two:

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 org.arpit.java2blog; public class PowerOfTwoMain { public static void main(String[] args) { System.out.println("128 is power of two : "+powerOfTwoGeneral(128)); System.out.println("64 is power of two : "+powerOfTwoBitwise(64)); System.out.println("22 is power of two : "+powerOfTwoBitwise(22)); System.out.println("22 is power of two : "+powerOfTwoGeneral(22)); } // Approach 1 public static boolean powerOfTwoGeneral(int n) { while(n%2==0) { n=n/2; } if(n==1) { return true; } else { return false; } } // Approach 2 public static boolean powerOfTwoBitwise(int n) { return (n & n-1)==0; } } |

When you run above code, you will get below results

1 2 3 4 5 6 |
128 is power of two : true 64 is power of two : true 22 is power of two : false 324 is power of two : false |

#### Join Our News Letter - Stay Updated

**Subscribe to Awesome Java Content**.