Skip to content

Commit 150bdaf

Browse files
committed
Add solution #1318
1 parent 86554c0 commit 150bdaf

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 1318. Minimum Flips to Make a OR b Equal to c
3+
* https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/
4+
* Difficulty: Medium
5+
*
6+
* Given 3 positives numbers a, b and c.
7+
* Return the minimum flips required in some bits of a and b
8+
* to make ( a OR b == c ). (bitwise OR operation).
9+
*
10+
* Flip operation consists of change any single bit 1 to 0
11+
* or change the bit 0 to 1 in their binary representation.
12+
*/
13+
14+
/**
15+
* @param {number} a
16+
* @param {number} b
17+
* @param {number} c
18+
* @return {number}
19+
*/
20+
var minFlips = function(a, b, c, flips = 0) {
21+
[a, b, c] = [a, b, c].map(x => x.toString(2).padStart(32, 0));
22+
23+
for (let i = 0; i < c.length; i++) {
24+
if ((+a[i] | +b[i]) !== +c[i]) {
25+
if (((+a[i] ^ 1) | +b[i]) === +c[i] || (+a[i] | (+b[i] ^ 1)) === +c[i]) flips++;
26+
else if (((+a[i] ^ 1) | (+b[i] ^ 1)) === +c[i]) flips += 2;
27+
}
28+
}
29+
30+
return flips;
31+
};

0 commit comments

Comments
 (0)