LeetCode 75
Minimum Flips to Make a OR b Equal to c
- Problem
- LC 1318
- Topic
- Bit Manipulation
- File
- official75_LC1318MinimumFlipsToMakeAORbEqualToC.java
- Path
- pkg5leetcode/official75/official75_LC1318MinimumFlipsToMakeAORbEqualToC.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC1318MinimumFlipsToMakeAORbEqualToC.java
- Approach
- Per bit compare a|b to c; count mismatches.
- Complexity
- Time O(1), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Minimum Flips to Make a OR b Equal to c | LC 13185 * APPROACH: Per bit compare a|b to c; count mismatches.6 * COMPLEXITY: Time O(1), Space O(1)7 */8public class official75_LC1318MinimumFlipsToMakeAORbEqualToC {9 static int minFlips(int a, int b, int c) {10 int flips = 0;11 for (int i = 0; i < 32; i++) {12 int bitC = (c >> i) & 1;13 int bitA = (a >> i) & 1;14 int bitB = (b >> i) & 1;15 if (bitC == 1) {16 if (bitA == 0 && bitB == 0) flips++;17 } else {18 if (bitA == 1 && bitB == 1) flips += 2;19 else if (bitA == 1 || bitB == 1) flips++;20 }21 }22 return flips;23 }24 25 public static void main(String[] args) {26 check(minFlips(2, 6, 5) == 3, "case1");27 check(minFlips(4, 2, 7) == 1, "case2");28 check(minFlips(1, 2, 3) == 0, "case3");29 System.out.println("all tests passed");30 }31 32 static void check(boolean cond, String name) {33 if (!cond) throw new AssertionError("FAILED: " + name);34 System.out.println(" PASS " + name);35 }36}