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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find Next Sparse Number
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Check if a number has same number of set and unset bits
- Check whether a given number is even or odd
- Check if all bits of a number are set
- Check if a number can be expressed as 2^x + 2^y
- Check if a number is power of 8 or not
- Check if a number is Bleak
- Check whether the number has only first and last bits set
- Check whether the number has only first and last bits set | Set 2
- Check whether the given number is Wagstaff prime or not
- Check if a number has two adjacent set bits
- Check if the Xor of the frequency of all digits of a number N is zero or not
- Check if a Number is Odd or Even using Bitwise Operators
- Check a number is odd or even without modulus operator