Is A Power Of 2
1. You are given a number n.Input Format
2. You have to check whether it is a power of 2 or not.
A number nOutput Format
true/falseQuestion Video
1 <= n <= 10^9Sample Input
1024Sample Output
true
-
Editorial
In this problem, we have to determine whether a given integer input is a power of 2 or not.
For example, 1, 2, 4, 8, 16, 32 ... are numbers that are a power of 2.
We will implement a constant time solution with bit manipulation.
A common trait of any number which is a power of 2 is that it has only one set bit and the rest of all bits are unset and that set bit is the MSB bit.
We can approach the problem in multiple ways. One way is to count the number of set bits using Kerninghams algorithm. Another approach deals with taking an AND operation with (N - 1). This works as N should be of type 1 0 0 0 ... while (N - 1) will be of type 0 1 1 1 ... so their AND operation must be zero for the number to be a power of 2. Another approach can be to get the rightmost set bit mask of the number and as there is only one set bit for a power of 2 number so the value of the RSB mask must be equal to the number N for it to be a power of 2.
Time Complexity: O(1)
The time complexity for the function is constant.
Space Complexity: O(1)
The space complexity for the function is constant.
-
Asked in Companies
-
Related Topics