|
| 1 | +// 2220. Minimum Bit Flips to Convert Number |
| 2 | +// 🟢 Easy |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimum-bit-flips-to-convert-number/ |
| 5 | +// |
| 6 | +// Tags: Bit Manipulation |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// One solution is to XOR the input numbers and return the number of 1 bits in the result. |
| 11 | + /// |
| 12 | + /// Time complexity: O(log2(max(m,n))) - The built-in count_ones function's complexity. |
| 13 | + /// Space complexity: O(1) - Constant extra memory used. |
| 14 | + /// |
| 15 | + /// Runtime 0 ms Beats 100% |
| 16 | + /// Memory 2.08 MB Beats 84% |
| 17 | + #[allow(dead_code)] |
| 18 | + pub fn min_bit_flips_built_in(start: i32, goal: i32) -> i32 { |
| 19 | + (start ^ goal).count_ones() as _ |
| 20 | + } |
| 21 | + |
| 22 | + /// A neat method using Brian Kernighan’s Algorithm, it counts one values skipping values that |
| 23 | + /// we are not interested on. |
| 24 | + /// |
| 25 | + /// Time complexity: O(log2(n)) - Where n is the result. |
| 26 | + /// Space complexity: O(1) - Constant extra memory used. |
| 27 | + /// |
| 28 | + /// Runtime 0 ms Beats 100% |
| 29 | + /// Memory 2.19 MB Beats 15% |
| 30 | + #[allow(dead_code)] |
| 31 | + pub fn min_bit_flips(start: i32, goal: i32) -> i32 { |
| 32 | + let mut rem = start ^ goal; |
| 33 | + let mut res = 0; |
| 34 | + while rem > 0 { |
| 35 | + rem &= rem - 1; |
| 36 | + res += 1; |
| 37 | + } |
| 38 | + res |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// Tests. |
| 43 | +fn main() { |
| 44 | + let tests = [(10, 7, 3), (3, 4, 3)]; |
| 45 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 46 | + let mut success = 0; |
| 47 | + for (i, t) in tests.iter().enumerate() { |
| 48 | + let res = Solution::min_bit_flips(t.0, t.1); |
| 49 | + if res == t.2 { |
| 50 | + success += 1; |
| 51 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 52 | + } else { |
| 53 | + println!( |
| 54 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 55 | + i, t.1, res |
| 56 | + ); |
| 57 | + } |
| 58 | + } |
| 59 | + println!(); |
| 60 | + if success == tests.len() { |
| 61 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 62 | + } else if success == 0 { |
| 63 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 64 | + } else { |
| 65 | + println!( |
| 66 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 67 | + tests.len() - success |
| 68 | + ) |
| 69 | + } |
| 70 | +} |
0 commit comments