[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 => 소수점 아래 다 버리고 오직 몫만
비트연산자를 쓰면 더 간단할까..? 싶지만
비트 계산은 하나도 몰라서 포기~
Author And Source
이 문제에 관하여([leetcode-python3] 191. Number of 1 Bits), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jsh5408/leetcode-python3-191.-Number-of-1-Bits저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)