![]() |
VOOZH | about |
Write a function to check if a given number is Sparse or not.
A number is said to be a sparse number if in the binary representation of the number no two or more consecutive bits are set.
Example:
Input: x = 72
Output: true
Explanation: Binary representation of 72 is 01001000.
There are no two consecutive 1's in binary representationInput: x = 12
Output: false
Explanation: Binary representation of 12 is 1100.
Third and fourth bits (from end) are set.
Naive Approach: The idea is to check the consecutive bits of the number until the number becomes 0.
Not Sparse
Time Complexity: O(Log2n)
Auxiliary Space: O(1)
Efficient Approach: To solve the problem follow the below idea:
If we observe carefully, then we can notice that if we can use bitwise AND of the binary representation of the "given number, then it's "right-shifted number"(i.e., half the given number) to figure out whether the number is sparse or not. The result of AND operator would be 0 if the number is sparse and non-zero if not sparse.
Below is the implementation of the above approach:
1 0 1 0
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: Instead of the right shift, we could have used the left shift also, but the left shift might lead to an overflow in some cases.