Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Input: [5,7] Output: 4
Input: [0,1] Output: 0
impl Solution {
pub fn range_bitwise_and(m: i32, n: i32) -> i32 {
let mut result = n;
for i in m..n {
result &= i;
}
result
}
}
impl Solution {
pub fn range_bitwise_and(m: i32, n: i32) -> i32 {
let mut n = n;
while n > m {
n &= n - 1;
}
n
}
}
impl Solution {
pub fn range_bitwise_and(m: i32, n: i32) -> i32 {
if n > m {
Self::range_bitwise_and(m >> 1, n >> 1) << 1
} else {
m
}
}
}
impl Solution {
pub fn range_bitwise_and(m: i32, n: i32) -> i32 {
let mut result = 0;
let mut mask = 1 << 30;
while mask != 0 && m & mask == n & mask {
result |= m & mask;
mask >>= 1;
}
result
}
}