This post is completed by 1 user
|
Add to List |
330. Check if Given Number is power of 2
Objective: Given a number, write a program to find if number is power of two.
Example:
N = 5 Output: false. N = 8 Output: true (23) N = 512 Output: true (29)
Approach:
This problem can be solved in multiple ways; we will discuss three solutions here.
- Log2 Method
- Check the Remainder
- Convert number to bits
Log2 Method:
Get the log of the number with base 2 and if outcome is integer then number is power of 2.
Output:
Given number 6 is not power of 2 Given number 8 is power of 2 Given number 24 is not power of 2 Given number 512 is power of 2
Method - Check the Remainder:
Keep dividing the number by 2 till n =1, and during this iteration, if any time number%2 is non zero then the number is not the power of 2 else the number is the power of 2.
Output:
Given number 6 is not power of 2 Given number 8 is power of 2 Given number 24 is not power of 2 Given number 512 is power of 2
Method – Bit Manipulation
- Every number which is a power of 2 has only one bit set (4 = 1 0 0, 8 = 1 0 0 0, 16 = 1 0 0 0 0),
- Convert the given number into binary and count the number of set bits, if count > 1 then number is not power of 2 else the number is power of 2.
Output:
Given number 6 is not power of 2 Given number 8 is power of 2 Given number 24 is not power of 2 Given number 512 is power of 2
Reference: Here