- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

8, 12

8

- Related Questions & Answers
- Bitwise AND of Numbers Range in C++
- Python - Find the number of prime numbers within a given range of numbers
- Program to find out the number of special numbers in a given range in Python
- Create list of numbers with given range in Python
- Find a range of composite numbers of given length in C++
- Maximum Bitwise AND pair from given range in C++
- C++ Program to Generate Randomized Sequence of Given Range of Numbers
- PHP program to find the sum of odd numbers within a given range
- Program to find count of numbers having odd number of divisors in given range in C++
- Bitwise and (or &) of a range in C++
- Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers
- Write a Golang program to find prime numbers in a given range
- C++ Program to find Numbers in a Range with Given Digital Root
- Bitwise OR (or - ) of a range in C++
- How to find Kaprekar numbers within a given range using Python?

Advertisements