Old Wei wins the offer to take you to learn --- Brush title series (number 11 in binary 1)

11. The number of binary 1

problem:

An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.

solve:

thought:

If a non-zero integer, then this is an integer of at least 1. If we subtract the integer 1, then the original integer in the rightmost 1 will be changed to 0, the original becomes (0, then there's a 1 followed if the rightmost) 1 in all 01 will be back. All remaining bits will not be affected.
For example: a binary number 1100, from the third to the right of the number is in a rightmost 1. After subtracting 1, the third becomes 0, it later became two of 0 1 1 while the front remains unchanged, so the result is 1011. We found that the results of minus one is to a rightmost 1 bits are all starting to take backwards. This time the results after the original integer if we then do with the operation and subtract 1 from the original integer rightmost 1 the one who began all the bits will become 0. Such as the 1100 & 1011 = 1000. That put an integer minus 1, and then to do with the original integer arithmetic, the integer will rightmost 1 becomes 0. Then a binary integer of 1 how many, how much can be times such an operation.

python code:

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        count=0
        if(n<0):
            n=n&0xffffffff
        while(n):
            count+=1
            n=(n-1)&n
        return count
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104886985