Thursday, May 30, 2013

How to Check if Integer Number is Power of Two in Java - 3 examples

How to check if an integer number is 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

Power of Two number checking in JavaIn 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.


Related Java Coding Questions from Javarevisited Blog

8 comments :

Anonymous said...

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

saurabh chopra said...

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);

}

}

Kumar Bhatia said...

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/

Anonymous said...

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

Klāvs Priedītis said...

public static boolean isPowerOfTwo(int i){
if (i==0) return false;
int d = Math.abs(i);
return (d & (d-1)) == 0;
}

Anonymous said...

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

Ravi said...

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

Anonymous said...

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)

Post a Comment