티스토리 뷰

https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/

 

Sort Integers by The Number of 1 Bits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

int 형태의 숫자를 bit로 만들었을경우 1과 0으로 표현할 수 있다. ex) 7 -> 01

이때 나오는 1의 갯수로 int리스트를 정렬해주면 된다. 나는 countOneBit라는 함수를 만들어서 했지만

python에는

>>> bin(number)

전달받은 integer 혹은 long integer 자료형의 값을 이진수(binary) 문자열로 돌려준다. 

함수가 존재한다. 잘 써먹자.

 

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        def countOneBit(n):
            stack = []
            while n > 1:
                stack.append(n % 2)
                n //= 2
            stack.append(n)
            return stack.count(1)
        
        return list(sorted(arr, key = lambda x : (countOneBit(x), x)))

'ALGORITHM > LeetCode' 카테고리의 다른 글

[leetcode] subtree-of-another-tree.py  (0) 2022.05.28
[leetcode] count-items-matching-a-rule.py  (0) 2022.02.20
[leetcode] merge-two-sorted-lists.py  (0) 2021.12.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함