
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if bits in range L to R of two numbers are complement of each other or not in Python
Suppose we have two numbers x and y and a given range (left, right). We have to check whether all bits in range left to right in both the given numbers are complement of each other or not. We have to keep in mind that from right to left, so the least significant bit is considered to be at first position.
So, if the input is like x = 41 y = 54 left = 2 right = 5, then the output will be True, as binary representation of 41 and 54 are 101001 and 110110. The bits in range 2 to 5 of x and y are "1001" and "0110" which are complement of each other.
To solve this, we will follow these steps −
- temp := x XOR y
- return true when all bits in range (left, right) of temp is 1, otherwise false
Let us see the following implementation to get better understanding −
Example
def are_all_setbits_in_range(n, left, right): val = ((1 << right) - 1) ^ ((1 << (left - 1)) - 1) new_value = n & val if val == new_value: return True return False def solve(x, y, left, right): temp = x ^ y return are_all_setbits_in_range(temp, left, right) x = 41 y = 54 left = 2 right = 5 print(solve(x, y, left, right))
Input
41, 54, 2, 5
Output
True
- Related Articles
- Javascript Program to Check if two numbers are bit rotations of each other or not
- Check if strings are rotations of each other or not in Python
- Program to check strings are rotation of each other or not in Python
- Write a program in JavaScript to check if two strings are anagrams of each other or not
- Check if one of the numbers is one’s complement of the other in Python
- A Program to check if strings are rotations of each other or not?
- JavaScript Program to Check if strings are rotations of each other or not
- How to check if two numbers (m,n) are amicable or not using Python?
- Check if all levels of two trees are anagrams or not in Python
- Queries to check if substring[L…R] is palindrome or not in C++ Program
- Check whether two strings are anagram of each other in Python
- How to check if two data frames same or not in R?
- Check if concatenation of two strings is balanced or not in Python
- Check if two strings are anagram of each other using C++
- Check if sum of divisors of two numbers are same in Python

Advertisements