Skip to content

Commit

Permalink
"Sort Integers by The Number of 1 Bits" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 30, 2023
1 parent a3da9c1 commit 53deda6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/sort_integers_by_the_number_of_1_bits.py
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))
17 changes: 17 additions & 0 deletions tests/test_sort_integers_by_the_number_of_1_bits.py
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

0 comments on commit 53deda6

Please sign in to comment.