less than 1 minute read

191. Number of 1 Bits

문제 링크

https://leetcode.com/problems/number-of-1-bits/description/

문제 설명

Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).

제한 사항

  • 1 <= n <= 2^31 - 1

입출력 예 #1

  1. Input : n = 11
  2. Output : 3
  3. Explanation : The input binary string 1011 has a total of three set bits.

입출력 예 #2

  1. Input : n = 128
  2. Output : 1
  3. Explanation : The input binary string 10000000 has a total of one set bit.

입출력 예 #3

  1. Input : n = 2147483645
  2. Output : 30
  3. Explanation : The input binary string 1111111111111111111111111111101 has a total of thirty set bits.

문제 풀이

입력받은 숫자를 2진수로 바꾸고 1의 개수를 출력한다.

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n).count('1')

Comments