【每日一题1109】比特求和

:woman_mage:给定一个正整数,请编写一个函数,计算它的二进制形式的所有数字的总和。

示例:
输入:1234,输出:5。因为10011010010

题目难度:简单
题目来源:codewars: Bit Counting

def count_bits(n: int) -> int:
    # 你的代码

assert count_bits(4) == 1
assert count_bits(9) == 2
assert count_bits(10) == 2
assert count_bits(1234) == 5
def count_bits(n: int) -> int:
    return sum([int(i) for i in '{0:b}'.format(n)])


assert count_bits(4) == 1
assert count_bits(9) == 2
assert count_bits(10) == 2
assert count_bits(1234) == 5

人生苦短,我学python

def count_bits(n:int)->int:
    return bin(n).count('1')
2 个赞
def count_bits(n: int) -> int:
    li = list(str(format(n, 'b')))
    data = 0
    for i in li:
        if i == '1':
            data += 1
    return data

assert count_bits(4) == 1
assert count_bits(9) == 2
assert count_bits(10) == 2
assert count_bits(1234) == 5

@fwj 666,直呼内行!

def count_bits(n: int) -> int:
    return str(format(n,'b')).count('1')

def count_bits(n: int) → int:
‘’’
给定一个正整数,请编写一个函数,计算它的二进制形式的所有数字的总和。

示例:
输入:1234,输出:5。因为10011010010
:param n:
:return:
'''
bin_num = bin(n)
# 二进制转str
bin_num_str = str(bin_num)
# 去掉二进制前面标识的ob前缀
bin_num_str = bin_num_str[2:]
print(bin_num_str)
# 转回二进制的int
bin_num = int(bin_num_str)
# 求和
sum = 0
data = bin_num
while data != 0:
    sum += data%10
    data = int(data/10)
return sum

def test_count_bits():
assert count_bits(1234) == 5
assert count_bits(1) == 1
pass

1 个赞
def count_bits(n):
    result = sum(int(i) for i in str(bin(n)) if i=="1")
    return result

内置bin函数,将正整数转换成二进制形式,再通过str函数转换成字符串,最后使用sum函数统计字符串中1的个数

def count_bits(n: int) -> int:
    return sum([int(i) for i in list(bin(n))[2:]])

assert count_bits(4) == 1
assert count_bits(9) == 2
assert count_bits(10) == 2
assert count_bits(1234) == 5
def count_bits(n: int) -> int:
    return sum([int(i) for i in str(bin(n))[2:]])

assert count_bits(4) == 1
assert count_bits(9) == 2
assert count_bits(10) == 2
assert count_bits(1234) == 5
def count_bits(n: int) -> int:
    # n_bin = bin(n)[2:]
    # sum = 0
    # for c in n_bin:
    #     sum += int(c)
    # return sum
    return sum([int(c) for c in bin(n)[2:]])

assert count_bits(4) == 1
assert count_bits(9) == 2
assert count_bits(10) == 2
assert count_bits(1234) == 5
public int countBit(int num){
        // 十进制转换为二进制
        // 拆分二进制为数组
        String[] str = Integer.toString(num, 2).split("");
        int sum =0;
        for (String  s: str) {
            sum += Integer.parseInt(s);
        }
        return sum;
    }