Problem 1318

Abstract / Summary

Given three integers a b and c count the bit positions where the bitwise OR of a and b does not match c.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1318.py

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        result = 0
        while a > 0 or b > 0 or c > 0:
            if c & 1:
                result += 1 - ((a | b) & 1)
            else:
                result += a & 1
                result += b & 1

            a >>= 1
            b >>= 1
            c >>= 1

        return result
15 lines | 376 bytes | submitted September 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (200k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method minFlips that computes the minimum number of bit flips required to make the bitwise OR of two integers a and b equal to a third integer c. The algorithm processes the three numbers bit by bit, from the least-significant position upward, accumulating the required flips in the variable result. The loop terminates when all three numbers have been fully shifted out, guaranteeing that every relevant bit has been examined.

Bitwise Traversal Loop

while a > 0 or b > 0 or c > 0:
    ...
    a >>= 1
    b >>= 1
    c >>= 1

The core of the solution is a while loop that continues as long as any of the three integers still contains set bits. Inside the loop the current least-significant bits of a, b, and c are examined. After the necessary calculations, each integer is right-shifted by one position (>>= 1), effectively moving to the next higher bit for the subsequent iteration. This design ensures that the algorithm adapts to inputs of varying bit lengths without requiring explicit length calculations.

Handling When the Target Bit Is 1

if c & 1:
    result += 1 - ((a | b) & 1)

When the current bit of c is 1, the desired outcome of a | b at that position must also be 1. The expression (a | b) & 1 extracts the resulting bit of the OR operation for the current position. If this bit is already 1, the subtraction yields 0, meaning no flip is needed. If the OR result is 0, the subtraction yields 1, indicating that exactly one flip (either in a or b) is required to turn the OR result to 1. This concise arithmetic captures the conditional increment without branching.

Handling When the Target Bit Is 0

else:
    result += a & 1
    result += b & 1

When the current bit of c is 0, the OR of a and b must also be 0. Consequently, both a and b must have a 0 at this position. The code adds the value of the least-significant bit of a (a & 1) and the least-significant bit of b (b & 1) directly to result. Each addition contributes 1 only when the corresponding bit is 1, reflecting the need to flip that bit to 0. This handles the case where both bits may need to be cleared independently.

Loop Termination

The loop condition a > 0 or b > 0 or c > 0 guarantees termination because each iteration right-shifts the three integers, steadily reducing their magnitude. Once all three numbers become zero, the condition fails and the loop exits. At that point, result holds the total number of flips required across all processed bits.

Edge Cases Handled

The algorithm naturally accommodates inputs where any of the numbers is zero. If a or b is zero, the corresponding bit extraction (a & 1 or b & 1) yields 0, and the shift operation leaves the value unchanged at zero, so no extra work is performed. When c is zero, the else branch is always taken, and the method correctly counts flips needed to clear any set bits in a or b. The loop also correctly processes cases where the numbers have different bit lengths; the shift-based termination ensures that trailing zeros in shorter numbers do not affect the result.

Performance Optimizations

The implementation relies exclusively on bitwise operators (&, |, >>) and integer arithmetic, which are executed in constant time at the CPU level. By avoiding any conversion to binary strings or auxiliary data structures, the method minimizes memory overhead and leverages the processor’s native bit manipulation capabilities. The use of a single accumulator variable (result) eliminates the need for intermediate collections, further reducing allocation pressure. The arithmetic expression 1 - ((a | b) & 1) replaces a conditional branch with a simple subtraction, which can improve pipeline predictability on modern CPUs. Overall, the design achieves a tight, low-level loop that processes each bit exactly once.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have three boxes of light switches. Each box contains a long row of switches that can be either on or off. The code looks at these three boxes one switch at a time, moving from the very last switch all the way to the first one.

For every position, the goal is to make the switches in the first two boxes match the switch in the third box. The code checks if the switch in the third box is flipped on. If it is, the code makes sure that at least one of the switches in the first two boxes is also on. If neither of them is on, it counts a flip to turn one of them on.

If the switch in the third box is flipped off, the code makes sure both switches in the first two boxes are also off. If any of those are currently on, it counts a flip to turn them off.

After checking a spot, the code slides over to look at the next switch by shifting everything down the line. This keeps happening until all the switches in all three boxes have been checked. The final count represents the total number of flips needed to make the boxes match up perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.00 | σ = 1.19

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fpdjsns C++
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fpdjsns C++
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
25 links | 14 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

11 solutions   September 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality