[leetcode-python3] 191. 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 above, the input represents the signed integer. -3.

Follow up:

If this function is called many times, how would you optimize it?

My Answer 1: Accepted (Runtime: 36 ms / Memory Usage: 14.2 MB)

class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        while n:
            count += n%2
            n = n//2
        return count

2로 나눴을 때 나머지는 0 또는 1
0은 더해져도 의미가 없으니까 나머지를 걍 싹다 더했다

n/2 => 소수점 아래까지 전부 나옴
n//2 => 소수점 아래 다 버리고 오직 몫만

비트연산자를 쓰면 더 간단할까..? 싶지만
비트 계산은 하나도 몰라서 포기~

좋은 웹페이지 즐겨찾기