How to check if an integer number is a power of 2 in Java is one of the popular programming interview question and has been asked in many interviews. Surprisingly, this problem which looks simple enough to answer, doesn't turn out that simple if for many developers. Many Java programmers, both freshers and less experienced, struggle to write code for a function, which can check if number is power of 2 or not. There could be many different reasons for that, but it’s expected to at least come up with brute force solution. For those who are familiar with bitwise operators in Java , how positive and negative numbers are represented in binary format, this exercise is quite easy. Since negative numbers are represented as 2's complement value in Java, you can easily find if any number is power of 2 or not by looking at its bit pattern. Remember checking for power of two is different than checking if number is even or odd, that’s another thing to note. A number can be even, but it’s not necessary to be a power of two, e.g. 6 is even but it’s not a power of two.

##
__3 ways to check if number is power of two or not__

In this article we will see 3 simple examples to check if any integer number is power of 2 or not. We have three methods, which uses bitwise operator, brute force way and bit shit operators to solve this problem. Method which uses bitwise operators can not check if zero is power of 2 or not, and only work for integer number which is greater than or equal to 1. here are code example of 3 simple method to find out if a number is power of 2 or not :

public class

*PowerOf2Test*{
public static void

**main**(String*args*[]) {
int[] numbers

**=**{*0*,*1*,*2*,*6*,*8*};**for**(int num

**:**numbers){

System

**.**out**.**println("isPowerOfTwo()-- is "**+**num**+**" power of two in Java :"**+**isPowerOfTwo(num));
System

**.**out**.**println("powerOfTwo()-- is "**+**num**+**" power of two in Java :"**+**powerOfTwo(num));
System

**.**out**.**println("checkPowerOfTwo()-- is "**+**num**+**" power of two in Java :"**+**checkPowerOfTwo(num));
System

**.**out**.**println("-----------------------------------------------------------");
}

}

/*

* checking if number is power of 2 using bit shift operator in java

* e.g. 4 in binary format is "0000 0000 0000 0000 0000 0000 0000 0100";

* and -4 is "1111 1111 1111 1111 1111 1111 1111 1100";

* and 4&-4 will be "0000 0000 0000 0000 0000 0000 0000 0100"

*/

private static boolean

**isPowerOfTwo**(int*number*) {**if**(number

**<**

*0*){

**throw**

**new**IllegalArgumentException("number: "

**+**number);

}

**if**((number

**&**

**-**number)

**==**number) {

**return**

*true*;

}

**return**

*false*;

}

/*

* checking if number is power of 2 using brute force

* starts with 1, multiplying with 2 it will eventually be same as original number

*/

private static boolean

**powerOfTwo**(int*number*){
int square

**=***1*;**while**(number

**>=**square){

**if**(number

**==**square){

**return**

*true*;

}

square

**=**square******2*;
}

**return**

*false*;

}

/*

* find if an integer number is power of 2 or not using bit shift operator

*/

private static boolean

**checkPowerOfTwo**(int*number*){**if**(number

**<**

*0*){

**throw**

**new**IllegalArgumentException("number: "

**+**number);

}

**return**((number

**&**(number

**-**

*1*))

**==**

*0*);

}

}

Output

**:**
isPowerOfTwo()

**--**is*0*power of two in Java**:***true*
powerOfTwo()

**--**is*0*power of two in Java**:***false*
checkPowerOfTwo()

**--**is*0*power of two in Java**:***true***-----------------------------------------------------------**

isPowerOfTwo()

**--**is*1*power of two in Java**:***true*
powerOfTwo()

**--**is*1*power of two in Java**:***true*
checkPowerOfTwo()

**--**is*1*power of two in Java**:***true***-----------------------------------------------------------**

isPowerOfTwo()

**--**is*2*power of two in Java**:***true*
powerOfTwo()

**--**is*2*power of two in Java**:***true*
checkPowerOfTwo()

**--**is*2*power of two in Java**:***true***-----------------------------------------------------------**

isPowerOfTwo()

**--**is*6*power of two in Java**:***false*
powerOfTwo()

**--**is*6*power of two in Java**:***false*
checkPowerOfTwo()

**--**is*6*power of two in Java**:***false***-----------------------------------------------------------**

isPowerOfTwo()

**--**is*8*power of two in Java**:***true*
powerOfTwo()

**--**is*8*power of two in Java**:***true*
checkPowerOfTwo()

**--**is*8*power of two in Java**:***true***-----------------------------------------------------------**

That’s all on this article about checking if a number I power of two or not. Let us know if you find another way to verify if number is power of two.

**Further Learning**

The Coding Interview Bootcamp: Algorithms + Data Structures

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

Related

**Java Coding Questions**from Javarevisited Blog
## 19 comments :

Is the brute force case, O(logN) complexity since you are multiplying by 2 each time? So log base 2 of N?

what about this???

public class PowerOftwo

{

public void powerOftwo(int number)

{

int num = number;

int d;

boolean flag = true;

while(num>1)

{

d = num % 2;

if(d%2!=0)

{

flag = false;

break;

}

num = num/2;

}

if(flag == true)

{

System.out.println("Number is a power of 2");

}

else

{

System.out.println("Number is not a power of 2");

}

}

public static void main(String[] args)

{

int number =16;

PowerOftwo obj = new PowerOftwo();

obj.powerOftwo(number);

}

}

Hi...i follow your blog while coding in my office...I really find your site useful...recently i joined your site as I am also creating a blog for technical implementations. Its in a very early stage..

Programming Language http://javacodeimpl.blogspot.in/

I often read, heard that power of 2 numbers have special significance in computer world, Why? Why most HashMap, HashSet use sizes which is power of 2? WHY

public static boolean isPowerOfTwo(int i){

if (i==0) return false;

int d = Math.abs(i);

return (d & (d-1)) == 0;

}

You may just use Integer.bitcount(number) == 1

WOW, Some clever tips checking integer is power of two, on comments :)

Take logs and cast one side as int and check if two sides are equal

public static boolean (int i)

return if((int)(Math.log(i+1)/Math.log(2)) - ((Math.log(i+1)/Math.log(2)))==0)

Thanks! Very good explanation. I can now get rid of Bitwise operator because of your Brute force (easy to understand).

return x == 0 ? false : x & (x - 1) == 0;

Is this possible?

class two

{

public static void power(int num)

{

int dup= num ;

while (dup > 2)

{

if (dup==2)

System.out.print (num+"is a power of two");

else if (dup < 2)

System.out.print(num+"is not a power of two");

dup=dup/2;

}

}

By

Ram

For the first and third method, I think there is a typo:

if(number<=0)

how can you display 0? And the result returns true?

@TCool, you are correct, its not <= but just less than, corrected it now

Comments have a semantic error. Bit shift operators are <<, >>, and >>>. Solutions are using bit AND operator &.

you know, you could've just used modulo on a number by dividing it by 2 (num%2). if it equals to 0, then it's an even/power by 2 ;)

20 % 2 equals 0, but 20 is not a power of 2.

In the third example (using the bit-shift operator) it checks to see if the number is less than 0 and raises an exception. Why!!

If the number is negative, then it's not a power of two (at least not a rational one), but that doesn't seem a good reason to declare number to be an illegal argument. Since the code already has a test why not test for number being less than 1 and returning false. (I'm pretty sure that 0 is 2 to the power of minus infinity, so I'd say that was out the scope of the question too).

Infinity is not a value.

@Miguel Duran, Exactly: So if you started with

if(number < 1) return false;

That would most likely be just as efficient an algorithm, but it would be more accurate (it would return false for 0) and it would be more orthogonal in the sense that it would return a consistent and correct answer over a wider range of input, rather than arbitrarily raising an exception.

## Post a Comment