From 56b6eee734c87545bd4600bad485dad4e5e6298b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 21 Feb 2024 14:54:47 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB201.=20Bitwise=20AND=20of=20N?= =?UTF-8?q?umbers=20Range=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/bitwise-and-of-numbers-range.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 rs/bitwise-and-of-numbers-range.rs diff --git a/rs/bitwise-and-of-numbers-range.rs b/rs/bitwise-and-of-numbers-range.rs new file mode 100644 index 0000000..0d66472 --- /dev/null +++ b/rs/bitwise-and-of-numbers-range.rs @@ -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 + } +}