본문 바로가기
IT/[Everyday]Coding

Number of 1 Bits

by Jang HyunWoong 2019. 1. 24.

Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

 

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.


My solution is


class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return "{0:b}".format(n).count('1')


반응형

'IT > [Everyday]Coding' 카테고리의 다른 글

SdkManager (Error) Warning: Could not create settings  (0) 2020.09.11
the longest palindromic substring  (0) 2019.03.06
Hamming Distance  (0) 2019.01.23
Jewels and Stones  (0) 2019.01.22
노트북 밧데리 수명 예측 연습  (0) 2018.02.20