mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
rs: add «201. Bitwise AND of Numbers Range»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
5d27f631e0
commit
56b6eee734
1 changed files with 21 additions and 0 deletions
21
rs/bitwise-and-of-numbers-range.rs
Normal file
21
rs/bitwise-and-of-numbers-range.rs
Normal file
|
@ -0,0 +1,21 @@
|
|||
impl Solution {
|
||||
fn discarded(mut left: i32, mut right: i32) -> i32 {
|
||||
let mut counter = 0;
|
||||
|
||||
while left != right {
|
||||
left >>= 1;
|
||||
right >>= 1;
|
||||
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
counter
|
||||
}
|
||||
|
||||
pub fn range_bitwise_and(left: i32, right: i32) -> i32 {
|
||||
let discarded_bits = Solution::discarded(left, right);
|
||||
let mask = !((1 << discarded_bits) - 1);
|
||||
|
||||
left & mask
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue