-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3e7aa6e
commit 1cc889f
Showing
3 changed files
with
43 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletions
9
src/page-13/1318. Minimum Flips to Make a OR b Equal to c/minFlips.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { minFlips } from './minFlips'; | ||
|
||
describe('1318. Minimum Flips to Make a OR b Equal to c', () => { | ||
test('minFlips', () => { | ||
expect(minFlips(2, 6, 5)).toBe(3); | ||
expect(minFlips(4, 2, 7)).toBe(1); | ||
expect(minFlips(1, 2, 3)).toBe(0); | ||
}); | ||
}); |
28 changes: 28 additions & 0 deletions
28
src/page-13/1318. Minimum Flips to Make a OR b Equal to c/minFlips.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
type MinFlips = (a: number, b: number, c: number) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const minFlips: MinFlips = (a, b, c) => { | ||
let flips = 0; | ||
|
||
for (let i = 0; i < 32; i++) { | ||
// 32 bits to cover 32-bit integers | ||
const bitA = (a >> i) & 1; | ||
const bitB = (b >> i) & 1; | ||
const bitC = (c >> i) & 1; | ||
|
||
if (bitC === 1) { | ||
// If bitC is 1, at least one of bitA or bitB must be 1 | ||
if (bitA === 0 && bitB === 0) { | ||
flips += 1; | ||
} | ||
} else { | ||
// If bitC is 0, both bitA and bitB must be 0 | ||
if (bitA === 1) flips += 1; | ||
if (bitB === 1) flips += 1; | ||
} | ||
} | ||
|
||
return flips; | ||
}; |