Skip to content

Commit 9da59be

Browse files
authored
Added solution for 2220
1 parent ff9d9a0 commit 9da59be

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Diff for: 02220. Minimum Bit Flips to Convert Number.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
impl Solution {
2+
// Convert both integers to strings of binary number format. If one of the strings is smaller than the other, prepend the appropriate number of zeroes to its start so that both the strings have same size. Then compare both strings character by character, returning the number of differences (or flips needed)
3+
pub fn min_bit_flips(start: i32, goal: i32) -> i32 {
4+
let mut differences = 0;
5+
let mut start_str = format!("{:b}", start);
6+
let mut goal_str = format!("{:b}", goal);
7+
let start_str_len = start_str.len();
8+
let goal_str_len = goal_str.len();
9+
if start_str_len > goal_str_len {
10+
goal_str = format!("{}{}", "0".repeat(start_str_len - goal_str_len), goal_str)
11+
} else if goal_str_len > start_str_len {
12+
start_str = format!("{}{}", "0".repeat(goal_str_len - start_str_len), start_str)
13+
}
14+
15+
for i in 0..start_str.len() {
16+
if start_str.chars().nth(i).unwrap() != goal_str.chars().nth(i).unwrap() {
17+
differences += 1;
18+
}
19+
}
20+
21+
return differences;
22+
}
23+
}

0 commit comments

Comments
 (0)