Check whether all the bits are set in the given range
Given a non-negative number n and two values l and r. The problem is to check whether all the bits are set or not in the range l to r in the binary representation of n.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples:
Input : n = 22, l = 2, r = 3
Output : Yes
(22)10 = (10110)2
The bits in the range 2 to 3 are all set.
Input : n = 47, l = 2, r = 5
Output : No
(47)10 = (101111)2
The bits in the range 2 to 5 are all not set.
Approach: Following are the steps:
- Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number num having r number of bits and bits in the range l to r are the only set bits.
- Calculate new_num = n & num.
- If num == new_num, return “Yes” (all bits are set in the given range).
- Else return “No” (all bits are not set in the given range).
C++
#include <bits/stdc++.h>
using namespace std;
string allBitsSetInTheGivenRange(unsigned int n,
unsigned int l, unsigned int r)
{
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
int new_num = n & num;
if (num == new_num)
return "Yes" ;
return "No" ;
}
int main()
{
unsigned int n = 22;
unsigned int l = 2, r = 3;
cout << allBitsSetInTheGivenRange(n, l, r);
return 0;
}
|
Java
class GFG {
static String allBitsSetInTheGivenRange( int n,
int l, int r)
{
int num = (( 1 << r) - 1 ) ^ (( 1 <<
(l - 1 )) - 1 );
int new_num = n & num;
if (num == new_num)
return "Yes" ;
return "No" ;
}
public static void main (String[] args)
{
int n = 22 ;
int l = 2 , r = 3 ;
System.out.print(allBitsSetInTheGivenRange(
n, l, r));
}
}
|
Python3
def allBitsSetInTheGivenRange(n, l, r):
num = (( 1 << r) - 1 ) ^ (( 1 << (l - 1 )) - 1 )
new_num = n & num
if (num = = new_num):
return "Yes"
return "No"
n, l, r = 22 , 2 , 3
print (allBitsSetInTheGivenRange(n, l, r))
|
C#
PHP
Javascript
Output:
Yes
Time Complexity – O(1)
Space Complexity – O(1)
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...