- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Bitwise and (or &) of a range in C++
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.
Example
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); }
Output
0
- Related Articles
- Bitwise OR (or - ) of a range in C++
- Bitwise AND of Numbers Range in C++
- Maximum Bitwise AND pair from given range in C++
- Program to find bitwise AND of range of numbers in given range in Python
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- Bitwise AND and OR in Arduino
- Bitwise OR of N binary strings in C++
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- What is Bitwise OR in C++?
- Queries for bitwise AND in the index range [L, R] of the given Array using C++
- Maximize the bitwise OR of an array in C++
- Bitwise OR operation between the elements of BitArray in C#
- Bitwise exclusive OR operation between the elements of BitArray in C#
- Number of pairs with Bitwise OR as Odd number in C++
- Print bitwise AND set of a number N in C++
