Why is it failing, Is there any other thing that we can add to the same logic to make it correct.
It fails at left=6 right=7
Here is the code snippet:
class Solution {
public static int log2(int N)
{
// calculate log2 N indirectly
// using log() method
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
public int rangeBitwiseAnd(int left, int right) {
int res=1;
int lower=log2(left);
int higher = log2(right);
// System.out.print(higher);
if(left==right)
return left;
if(lower != higher){
return left&(int)Math.pow(2,higher);
}
else{
return (int)Math.pow(2,higher);
}
}
}
Your logic is incorrect; it is not sufficient to only check the most significant bits. Instead, you need to find the longest matching prefix in the binary representation of the endpoints. In addition, the
Integer.highestOneBitutility method can be used instead of floating-point math.Alternatively, an iterative solution: