Please implement a function, input an integer, and output the number of 1s in the binary representation of the number. For example, representing 9 as binary is 1001, and 2 bits are 1. Therefore, if you enter 9, the function outputs 2.
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: In the input binary string 00000000000000000000000000001011, there are three bits of '1'.
Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: In the input binary string 00000000000000000000000010000000, there is a total of '1'
Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: In the input binary string 11111111111111111111111111111101, a total of 31 bits are '1'.
Source: LeetCode
Link: https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
Copyright belongs to the deduction network Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
Idea 1: Judging odd and even numbers, dividing by 2
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
while n:
if n & 1 == 1:
ans += 1
n //= 2
return ans
Idea 2: Ingenious use (n-1) & n
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
while n:
ans += 1
n &= (n-1)
return ans