Skip to content

Commit 34c3afa

Browse files
author
Gonzalo Diaz
committed
[Hacker Rank] Interview Preparation Kit: Miscellaneous: Flipping bits. New way to solve ✅.
1 parent 2991d6b commit 34c3afa

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-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: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# pylint: disable=line-too-long
2+
# @link Problem definition [[docs/hackerrank/interview_preparation_kit/miscellaneous/flipping-bits.md]] # noqa
3+
# @see Solution Notes: [[docs/hackerrank/interview_preparation_kit/miscellaneous/flipping-bits-alt-solution-notes.md]] # noqa
4+
# pylint: enable=line-too-long
5+
6+
def flippingBitsAlt(number: int) -> int:
7+
return ~number & 0xFFFFFFFF

src/hackerrank/interview_preparation_kit/miscellaneous/flipping_bits_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from ....lib.loader import loadTestCases
55
from .flipping_bits import flippingBits
6+
from .flipping_bits_alt import flippingBitsAlt
67

78
FILE_PATH = str(Path(__file__).resolve().parent)
89

@@ -22,3 +23,8 @@ def test_flipping_bits(self):
2223
flippingBits(_tt['input']), _tt['answer'],
2324
f"{_} | flippingBits({_tt['input']}) must be "
2425
f"=> {_tt['answer']}")
26+
27+
self.assertEqual(
28+
flippingBitsAlt(_tt['input']), _tt['answer'],
29+
f"{_} | flippingBitsAlt({_tt['input']}) must be "
30+
f"=> {_tt['answer']}")

0 commit comments

Comments
 (0)