- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 of Numbers Range in C++
Suppose we have a range [m, n] where 0 <= m <= n <= 2147483647. We have to find the bitwise AND of all numbers in this range, inclusive. So if the range is [5, 7], then the result will be 4.
To solve this, we will follow these steps −
i := 0
while m is not n, then
m := m/2, n := n / 2, increase i by 1
return m after shifting to the left i times.
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int rangeBitwiseAnd(int m, int n) { int i = 0; while(m != n){ m >>= 1; n >>= 1; i++; } return m << i; } }; main(){ Solution ob; cout << (ob.rangeBitwiseAnd(5,7)); }
Input
5 7
Output
4
Advertisements