A number is said to be a sparse number if in binary representation of the number no two or more consecutive bits are set. Write a function to check if a given number is Sparse or not.
Input: x = 72 Output: true Explanation: Binary representation of 72 is 01001000. There are no two consecutive 1's in binary representation Input: x = 12 Output: false Explanation: Binary representation of 12 is 1100. Third and fourth bits (from end) are set.
We strongly recommend that you click here and practice it, before moving on to the solution.
If we observer carefully, then we can notice that if we can use bitwise AND of binary representation of the “given number its “right shifted number”(i.e., half the given number) to figure out whether the number is sparse or not. Result of AND operator would be 0 if number is sparse and non-zero if not sparse.
Below is the implementation of above idea.
1 0 1 0
Note: Instead of right shift, we could have used left shift also, but left shift might lead to overflow in some cases.
This article is contributed by Vimal Vestron. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Write an Efficient Method to Check if a Number is Multiple of 3
- Find the Number Occurring Odd Number of Times
- Check for Integer Overflow
- Write an Efficient C Program to Reverse Bits of a Number
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Compute modulus division by a power-of-2-number
- Find whether a given number is a power of 4 or not
- Add 1 to a given number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Swap bits in a given number
- Binary representation of a given number
- Check if a number is multiple of 9 using bitwise operators
- How to turn off a particular bit in a number?