
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Program to find bitwise AND of range of numbers in given range in Python
- Bitwise and (or &) of a range in C++
- Bitwise OR (or - ) of a range in C++
- Maximum Bitwise AND pair from given range in C++
- How to bitwise XOR of hex numbers in Python?
- Queries for bitwise AND in the index range [L, R] of the given Array using C++
- Swapping numbers using bitwise operator in C
- Bitwise Right/ left shift numbers in Arduino
- Generating a range of numbers in MySQL?
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Maximum of four numbers without using conditional or bitwise operator in C++
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- Prime numbers in a range - JavaScript
- Generating range of numbers 1…n in SAP HANA
- Create list of numbers with given range in Python

Advertisements