반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 191 | Number of 1 Bits | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/number-of-1-bits/
문제
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:
- Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.
조건
- The input must be a binary string of length 32.
내 풀이
python에는 이진수로 바꿔주는 bin이라는 함수가 있다.
이 함수를 사용하면 bin(11) → 0b1011이런 식으로 바꿔준다.
이를 str로 바꾼 후에 1의 수를 세면 된다.
코드
class Solution:
def hammingWeight(self, n: int) -> int:
return str(bin(n)).count('1')
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 867 | Transpose Matrix | Python (0) | 2022.06.02 |
---|---|
[LeetCode] 29 | Divide Two Integers | Python (0) | 2022.05.30 |
[LeetCode] 354 | Russian Doll Envelopes | Python (0) | 2022.05.25 |
[LeetCode] 474 | Ones and Zeros | Python (0) | 2022.05.23 |
[LeetCode] 329 | Longest Increasing Path in a Matrix | Python (0) | 2022.05.19 |
Comments