Skip to content

Commit 88d31be

Browse files
authored
Merge pull request #736 from sir-gon/feature/flipping_bits_alternative
[Hacker Rank] Interview Preparation Kit: Miscellaneous: Flipping bits…
2 parents 74093ea + de6e445 commit 88d31be

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# [Miscellaneous: Flipping bits](https://www.hackerrank.com/challenges/flipping-bits)
2+
3+
- Difficulty: `#easy`
4+
- Category: `#ProblemSolvingBasic` `#BitManipulation`
5+
6+
## Using bitwise operations
7+
8+
The bitwise NOT operator (~) flips all bits of the number.
9+
10+
The & 0xFFFFFFFF ensures that we only keep the last 32 bits,
11+
effectively simulating a 32-bit unsigned integer.
12+
13+
This is a more efficient and concise way to achieve the same result
14+
as the original code, without needing to convert to binary strings.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/**
2+
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/miscellaneous/flipping-bits.md]]
3+
* @see Solution notes [[docs/hackerrank/interview_preparation_kit/miscellaneous/flipping-bits-alt-solution-notes.md]]
4+
*/
5+
6+
function flippingBitsAlt(n) {
7+
// eslint-disable-next-line no-bitwise
8+
return ~n >>> 0;
9+
}
10+
11+
export default { flippingBitsAlt };
12+
export { flippingBitsAlt };
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { describe, expect, it } from '@jest/globals';
2+
import { logger as console } from '../../../logger.js';
3+
4+
import { flippingBitsAlt } from './flipping-bits-alt.js';
5+
6+
import TEST_CASES from './flipping-bits.testcases.json';
7+
8+
describe('flipping bits', () => {
9+
it('flipping bits test cases', () => {
10+
expect.assertions(10);
11+
12+
let totalTestsCount = 0;
13+
14+
TEST_CASES.forEach((testSet) => {
15+
testSet.tests.forEach((test) => {
16+
const answer = flippingBitsAlt(test.input);
17+
18+
console.debug(
19+
`flippingBitsAlt(${test.input}) solution found: ${answer}`
20+
);
21+
22+
expect(answer).toStrictEqual(test.expected);
23+
24+
totalTestsCount += 1;
25+
});
26+
});
27+
28+
expect(TEST_CASES).toHaveLength(3);
29+
expect(totalTestsCount).toBe(8);
30+
});
31+
});

0 commit comments

Comments
 (0)