Skip to content

Commit 53deda6

Browse files
committedOct 30, 2023
"Sort Integers by The Number of 1 Bits" solution
1 parent a3da9c1 commit 53deda6

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed
 
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def number_of_ones(num: int) -> int:
2+
return bin(num)[2:].count("1")
3+
4+
5+
class Solution:
6+
def sortByBits(self, arr: list[int]) -> list[int]:
7+
return sorted(arr, key=lambda x: (number_of_ones(x), x))
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import pytest
2+
3+
from src.sort_integers_by_the_number_of_1_bits import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
"arr,expected",
8+
(
9+
([0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 4, 8, 3, 5, 6, 7]),
10+
(
11+
[1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1],
12+
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024],
13+
),
14+
),
15+
)
16+
def test_solution(arr, expected):
17+
assert Solution().sortByBits(arr) == expected

0 commit comments

Comments
 (0)