작심삼일

[LeetCode] 191 | Number of 1 Bits | Python 본문

스터디/코테

[LeetCode] 191 | Number of 1 Bits | Python

yun_s 2022. 5. 26. 10:20
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
반응형
Comments