
- 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
Program to find bitwise AND of range of numbers in given range in Python
Suppose we have two values start and end, we have to find the bitwise AND of all numbers in the range [start, end] (both inclusive).
So, if the input is like start = 8 end = 12, then the output will be 8 is 1000 in binary and 12 is 1100 in binary, so 1000 AND 1001 AND 1010 AND 1011 AND 1100 is 1000 which is 8.
To solve this, we will follow these steps −
- n := end - start + 1
- x := 0
- for b in range 31 to 0, decrease by 1, do
- if 2^b < n, then
- come out from loop
- if 2^b AND start AND end is non-zero, then
- x := x + (2^b)
- if 2^b < n, then
- return x
Example
Let us see the following implementation to get better understanding −
def solve(start, end): n = end - start + 1 x = 0 for b in range(31, -1, -1): if (1 << b) < n: break if (1 << b) & start & end: x += 1 << b return x start = 8 end = 12 print(solve(start, end))
Input
8, 12
Output
8
- Related Articles
- Bitwise AND of Numbers Range in C++
- Program to find out the number of special numbers in a given range in Python
- Create list of numbers with given range in Python
- Maximum Bitwise AND pair from given range in C++
- Python - Find the number of prime numbers within a given range of numbers
- Bitwise and (or &) of a range in C++
- Program to find count of numbers having odd number of divisors in given range in C++
- C++ Program to Generate Randomized Sequence of Given Range of Numbers
- Find a range of composite numbers of given length in C++
- Write a Golang program to find prime numbers in a given range
- C++ Program to find Numbers in a Range with Given Digital Root
- PHP program to find the sum of odd numbers within a given range
- Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers
- Python program to generate random numbers within a given range and store in a list?
- C++ program to find numbers with K odd divisors in a given range

Advertisements