Check whether all the bits are unset in the given range | C ++ implementation to check whether all the bits are unset in the given range or not ; function to check whether all the bits are unset in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which could only have one or more set bits in the range l to r and nowhere else ; if true , then all bits are unset in the given range ; else all bits are not unset in the given range ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool 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 ( new_num == 0 ) return true ; return false ; } int main ( ) { unsigned int n = 17 ; unsigned int l = 2 , r = 4 ; if ( allBitsSetInTheGivenRange ( n , l , r ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }