Given two non-negative numbers a and b and two values l and r. The problem is to check whether all bits at corresponding positions in the range l to r in both the given numbers are complement of each other or not.
The bits are numbered from right to left, i.e., the least significant bit is considered to be at first position.
Input: a = 10, b = 5 l = 1, r = 3 Output: Yes (10)10 = (1010)2 (5)10 = (101)2 = (0101)2 All the bits in the range 1 to 3 are complement of each other. Input: a = 21, b = 13 l = 2, r = 4 Output: No (21)10 = (10101)2 (13)10 = (1101)2 = (1101)2 All the bits in the range 2 to 4 are not complement of each other.
Approach: Below are the steps to solve the problem
- Calculate xor_value = a ^ b.
- Check whether all the bits are set or not in the range l to r in xor_value. Refer this post.
Below is the implementation of the above approach.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check if one of the numbers is one's complement of the other
- Check whether all the bits are set in the given range
- Check whether all the bits are unset in the given range or not
- Check whether all the bits are unset in the given range
- Check whether bits are in alternate pattern in the given range
- Check whether bits are in alternate pattern in the given range | Set-2
- Print numbers in the range 1 to n having bits in alternate pattern
- Check whether XOR of all numbers in a given range is even or odd
- Subtraction of two numbers using 2's Complement
- Why are negative numbers stored as 2's complement?
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if all bits can be made same by flipping two consecutive bits
- Check if binary representation of a given number and its complement are anagram
- Print numbers having first and last bits as the only set bits
- Unset bits in the given range
- Toggle bits in the given range
- Count set bits in a range
- Copy set bits in a range
- Set bits in N equals to M in the given range.
- Set all the bits in given range of a number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.