Skip to content

Commit 48c30ea

Browse files
committed
src/bin/minimum-flips-to-make-a-or-b-equal-to-c.rs
1 parent 2eda669 commit 48c30ea

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Diff for: src/bin/minimum-flips-to-make-a-or-b-equal-to-c.rs

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
fn main() {
2+
assert_eq!(3, Solution::min_flips(2, 6, 5));
3+
}
4+
5+
struct Solution;
6+
7+
impl Solution {
8+
pub fn min_flips1(a: i32, b: i32, c: i32) -> i32 {
9+
let mut count = 0;
10+
11+
for i in 0..32 {
12+
let a1 = ((a as u32) << (31 - i)) >> 31;
13+
let b1 = ((b as u32) << (31 - i)) >> 31;
14+
let c1 = ((c as u32) << (31 - i)) >> 31;
15+
16+
if c1 == 0 {
17+
if (a1 == 1 && b1 == 0) || (a1 == 0 && b1 == 1) {
18+
count += 1;
19+
} else if a1 == 1 && b1 == 1 {
20+
count += 2;
21+
}
22+
} else {
23+
if a1 == 0 && b1 == 0 {
24+
count += 1;
25+
}
26+
}
27+
}
28+
count
29+
}
30+
31+
// 任何数 &1 都只会剩下最后位的数字
32+
pub fn min_flips(a: i32, b: i32, c: i32) -> i32 {
33+
let mut count = 0;
34+
35+
for i in 0..32 {
36+
let a1 = (a >> i) & 1;
37+
let b1 = (b >> i) & 1;
38+
let c1 = (c >> i) & 1;
39+
40+
if c1 == 0 {
41+
if (a1 == 1 && b1 == 0) || (a1 == 0 && b1 == 1) {
42+
count += 1;
43+
} else if a1 == 1 && b1 == 1 {
44+
count += 2;
45+
}
46+
} else {
47+
if a1 == 0 && b1 == 0 {
48+
count += 1;
49+
}
50+
}
51+
}
52+
count
53+
}
54+
}

0 commit comments

Comments
 (0)