This content originally appeared on DEV Community and was authored by Gopi Gorantala
In this lesson, we will try to check if the given number is a power of 2. We solve this by writing an efficient algorithm that takes an optimal amount of time.
Introduction
Let’s do another challenging question to check your understanding of Bitwise operators.
Example 01:
Input: 4
Output: True (As 4 is 2^2)
Example 02:
Input: 12
Output: False
Problem statement
Write a program to check if a given number is a power of 2 or not.
Let’s consider a number and find how the AND operator does this.
Input = 64
Output: True
Explanation
We solve by making use of the &
operator in computers. There are many ways to solve this, of which two approaches are simple, and one of them is a more complex but better solution.
Assume
n
is non-negative. We use the&
operator to achieve this.
Solution: Brute-force/naive approach
Hint: The exciting part of calculating the power of 2 is that they have a set-bit count equals to one.
Algorithm
Read the input value.
-
Repeatedly divide input with
2
.- if
n
not equal to1
and if it isodd
, we will returnfalse
. - else
true
.
- if
Here is what our algorithm will look like:
class IsPowerOf2 {
private static boolean helper(int n) {
if (n == 0) {
return false;
}
while (n != 1) {
if (n % 2 != 0) {
return false;
}
n >>= 1;
}
return true;
}
public static void main(String[] args) {
System.out.println(helper(6));
System.out.println(helper(8));
}
}
Complexity analysis
Time complexity: O(logn)
This takes log(n)
complexity. We can do better in constant time using the Brian Kernighan’s algorithm.
Space complexity: O(1)
The space complexity is O(1)
. No additional space is allocated.
Coding Exercise
First, take a close look at the code snippets above and think of a solution. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the solution section. Good luck!
class Solution{
public static boolean isPow2(int n){
// Write - Your - Code- Here
return false; // change this, return true/false based on inputs
}
}
If you've got the answer great! if not, its normal, practice similar problems and you'll get a good hold of bit manipulation tricks.
The solution will be explained in below.
Let's see how we make use of Brain Kernighan's algorithm to achieve this.
Solution review: Brian Kernighan’s algorithm
This is considered faster than the previous naive approach.
In this approach, we count the set bits. If a number is the power of 2, we know that only one set bit is present in its Binary representation.
In binary, we go from right to left with powers of 2.
For example:
2^0, 2^1, 2^2, 2^3, 2^4, and so on.
Algorithm
Before we talk about algorithmic steps, you should review the tabular form of steps that depicts the algorithm.
If
(n & (n - 1) == 0)
, returnTrue
.else,
False
.
Let’s visualize the values in the table below:
Let’s see a couple of examples:
n = 4 => 00000000 00000000 00000000 00000100
n - 1 = 3 => 00000000 00000000 00000000 00000011
-----------------------------------------------------------
(n & (n - 1)) = 0 => 00000000 00000000 00000000 00000000
-----------------------------------------------------------
(n&(n - 1))
, here this becomes 0
, which is true
. Hence, the number 4
is a power of 2.
n = 6 => 00000000 00000000 00000000 00000110
n - 1 = 5 => 00000000 00000000 00000000 00000101
-----------------------------------------------------------
(n & (n - 1)) = 4 => 00000000 00000000 00000000 00000100
-----------------------------------------------------------
(n&(n - 1))
is 4
, which is not equal to 0
. Hence, the number 6
is not a power of 2.
Let us take a look at the optimized approach.
Code
Here is the reasoning behind this solution.
class IsPowerOf2 {
public static void main(String[] args) {
System.out.println(helper(6));
System.out.println(helper(8));
}
private static boolean helper(int n) {
if (n == 0) {
return false;
}
return (n & (n - 1)) == 0;
}
}
We can further simplify this code into a single line shown below.
class IsPowerOf2 {
public static void main(String[] args) {
System.out.println(helper(6));
System.out.println(helper(8));
}
private static boolean helper(int n) {
return n != 0 && (n & (n - 1)) == 0;
}
}
Complexity analysis
Time complexity: O(1)
The run time depends on the number of 1-bits
in n
. In the worst case, all bits in n
are 1-bits
. In the case of a 32-bit
integer, the run time is O(1)
.
Space complexity: O(1)
The space complexity is O(1)
. No additional space is allocated.
Bit Manipulation:
Master how bit-level operations are computed. Understand that bit-level operations are based on all the arithmetic operations built-into all languages. These bit-tricks could help in competitive programming and coding interviews in running algorithms mostly in O(1)
time.
Checkout my course Master Bit Manipulation for Coding Interviews.
This content originally appeared on DEV Community and was authored by Gopi Gorantala
Gopi Gorantala | Sciencx (2022-02-19T13:19:58+00:00) Power of 2 – Java Solution. Retrieved from https://www.scien.cx/2022/02/19/power-of-2-java-solution/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.