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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find Next Sparse Number
- Check whether the given number is Wagstaff prime or not
- Check whether the binary equivalent of a number ends with given string or not
- Check whether all the bits are unset in the given range or not
- Check if a cycle of length 3 exists or not in a graph that satisfy a given condition
- Check if a number is power of 8 or not
- Check whether bitwise AND of a number with any subset of an array is zero or not
- Check if the Xor of the frequency of all digits of a number N is zero or not
- Check whether the binary equivalent of a number ends with "001" or not
- Find whether a given number is a power of 4 or not
- Check if two numbers are bit rotations of each other or not
- Efficiently check whether n is a multiple of 4 or not
- Check if concatenation of two strings is balanced or not
- Check if bits in range L to R of two numbers are complement of each other or not
- Check whether K-th bit is set or not
- Number whose XOR sum with given array is a given number k
- Check whether a given number is even or odd
- Check if binary representation of a given number and its complement are anagram
- Check if given number is a power of d where d is a power of 2
- Queries to check whether all the elements in the given range occurs even number of times