본문 바로가기
코딩 테스트/leetcode

Counting Bits

by ornni 2024. 6. 11.
728x90
반응형

첫번째 코드

 

bin()함수를 이용하여 이진수로 표현한 다음

그 이진수에 들어 있는 1의 개수를 센 후 더하여 answer 리스트에 더하는 방법을 이용한다.

 

class Solution:
    def countBits(self, n: int) -> List[int]:
        answer = []
        for i in range(n+1):
            count = 0
            s = bin(i)[2:]
            for j in s:
                if j == '1':
                    count += 1
            answer.append(count)
        return answer

 

통과!


링크

https://github.com/ornni/leetcode/tree/main/0338-counting-bits

 

leetcode/0338-counting-bits at main · ornni/leetcode

Collection of LeetCode questions to ace the coding interview! - Created using [LeetHub v3](https://github.com/raphaelheinz/LeetHub-3.0) - ornni/leetcode

github.com

 

반응형

'코딩 테스트 > leetcode' 카테고리의 다른 글

Minimum Number of Moves to Seat Everyone  (0) 2024.06.17
Range Sum of BST  (0) 2024.06.14
Search Insert Position  (0) 2024.06.13
Minimum Number Game  (0) 2024.06.05
Maximum Product of Two Elements in an Array  (0) 2024.05.27