- 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

In this problem, we are given two integer values a and b. And our task is to find the **bitwise and (&) of range from a to b**. This means we will have to find the value of a & a+1 & a+2 & … b-1 & b.

Let’s take an example to understand the problem,

**Input** − a = 3 , b = 8

**Output** − 0

**Explanation** − *3 & 4 & 5 & 6 & 7 & 8 = 0*

To solve the problem, a simple solution is starting from a and find bitwise and of all numbers by increasing one to b.

**More effective Solution,**

This is a more effective solution, this can be done using −

**Step1** − Flip LSB of b.

**Step2** − Compare the number with a and b, check if it is in range,

**Step 2.1** − if the number is greater than a flip its LSB gain.

**Step 2.2** − if it is not greater than a then number = result.

Now, **let**’s see the algorithm above in working −

**Example** − a = 3 and b = 8.

**Solution** −

**Step1** − b = 8 (1000), flipping LSB which is the only one in the number. The number becomes 0000 i.e. 0

**Step2** − 0 is less than 3, 0 is the result.

Now, let’s see the code to solve the problem,

#include <stdio.h> int main(){ long a, b; a = 3; b = 8; do{ b -= (b & -b); }while(a < b); printf("%li", b); }

0

- Related Questions & Answers
- Bitwise OR (or - ) of a range in C++
- Bitwise AND of Numbers Range in C++
- Maximum Bitwise AND pair from given range in C++
- What is JavaScript Bitwise AND (&) Operator?
- Program to find bitwise AND of range of numbers in given range in Python
- Bitwise AND and OR in Arduino
- What is Bitwise AND Operator (&) in JavaScript?
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Bitwise OR of N binary strings in C++
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- What is Bitwise OR in C++?
- Maximize the bitwise OR of an array in C++
- Bitwise OR operation between the elements of BitArray in C#
- Queries for bitwise AND in the index range [L, R] of the given Array using C++
- Print bitwise AND set of a number N in C++

Advertisements