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 :
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