Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example:
Input: a=5,b=7
Output: 4
Approach
Java
public class BitwiseANDNumbersRange {public static void main(String[] args) {int a = 5;int b = 7;System.out.println(rangeBitwiseAnd(a, b));}// function to find the// MSB position of the numberstatic int MSB(int n) {int pos = -1;while (n>0) {n = n >> 1;pos++;}return pos;}// function to find the bitwise and of// range from m to nstatic int rangeBitwiseAnd(int m, int n) {int res = 0;while (m>0 && n>0) {int pos1 = MSB(m);int pos2 = MSB(n);// if MSB of both are not same then break// because and of the range will be zeroif (pos1 != pos2)break;// else update the resultres += 1 << pos1;// subtract MSB from both the numberm -= 1 << pos1;n -= 1 << pos1;}// return the final answerreturn res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the//MSB position of the numberint MSB(int n){int pos=-1;while(n){n=n>>1;pos++;}return pos;}//function to find the bitwise and of//range from m to nint rangeBitwiseAnd(int m, int n){int res=0;while(m&&n){int pos1=MSB(m);int pos2=MSB(n);//if MSB of both are not same then break//because and of the range will be zeroif(pos1!=pos2)break;//else update the resultres+=1<<pos1;//subtract MSB from both the numberm-=1<<pos1;n-=1<<pos1;}//return the final answerreturn res;}int main(){int a=5;int b=7;cout<<rangeBitwiseAnd(a,b);return 0;}
No comments:
Post a Comment