
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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