Title Description
An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement. (Here, only the leading 32)
-2 complement: first ones complement -2 10000 .. . 10 - "11111 .. . 01
Then twos complement, i.e., the end of the inverted plus 1: 111 .. . 10
method 1:
. 1 # - * - Coding: UTF-. 8 - * - 2 class Solution: . 3 DEF NumberOf1 (Self, n-): . 4 COUNT = 0 . 5 in front of n = n & 0xFFFFFFFF #python the number of how many bits we do not understand, taken 32 it . 6 for I in STR (bin (n-)): . 7 IF I == ' . 1 ' : . 8 COUNT + =. 1 . 9 return COUNT
Method 2:
# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): count = 0 for i in range(32): mask = 1<<i if mask & n!=0: count+=1 return count
Method 3:
1 class Solution: 2 def NumberOf1(self, n): 3 count=0 4 n = n&0xFFFFFFFF 5 while n>0: 6 n = n&(n-1) 7 count+=1 8 return count
2019-12-02 09:51:36