-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
"Sort Integers by The Number of 1 Bits" solution
- Loading branch information
Showing
2 changed files
with
24 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
def number_of_ones(num: int) -> int: | ||
return bin(num)[2:].count("1") | ||
|
||
|
||
class Solution: | ||
def sortByBits(self, arr: list[int]) -> list[int]: | ||
return sorted(arr, key=lambda x: (number_of_ones(x), x)) |
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,17 @@ | ||
import pytest | ||
|
||
from src.sort_integers_by_the_number_of_1_bits import Solution | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"arr,expected", | ||
( | ||
([0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 4, 8, 3, 5, 6, 7]), | ||
( | ||
[1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1], | ||
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024], | ||
), | ||
), | ||
) | ||
def test_solution(arr, expected): | ||
assert Solution().sortByBits(arr) == expected |