Skip to main content
Back to problems
#1318
Medium Algorithms

Minimum flips to make a or b equal to c

Bit Manipulation
71.9% acceptance
Feb 25, 2026
2136
111
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_flips(a: i32, b: i32, c: i32) -> i32 {
    let mut flips = 0;
    for i in 0..30 {
      let ai = (a >> i) & 1;
      let bi = (b >> i) & 1;
      let ci = (c >> i) & 1;
      if ci == 1 {
        // Need at least one of ai, bi to be 1
        if ai == 0 && bi == 0 { flips += 1; }
      } else {
        // Need both ai and bi to be 0
        flips += ai + bi;
      }
    }
    flips
  }
}