二进制中1的个数

题目

实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如9的二进制是1001,有2位是1。因此输入9,该函数输出2。

Python题解

def num_of_1_in_binary(n):
    cnt = 0
    while n:
        cnt += 1
        n = n & (n - 1)
    return cnt

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/79815819