Written test questions - the number of digits in binary 1

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        flag=1
        print(type(flag))
        count=0
        maxBit=32
        for i in range(maxBit):
            if n & flag:
                count+=1
            flag=flag<<1
        return count
Starting from the end, it is calculated whether it is 1, if so, the counter is incremented by one, and then the flag bit is shifted to the left and compared with the next bit.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325708958&siteId=291194637