【每日一题0924】个位数

:mage:t2:已知一个正整数,我们的任务是编写一个函数,计算得到个位数。计算规则是:先将数字转成二进制形式,然后将所有的0和1分解后汇总求和,如果是个位数则返回,否则继续分解再求和,直至得到的是个位数结果。
示例:
输入:5665,输出:5。
解释:因为5665的二进制是1011000100001,汇总求和结果是5。

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

def single_digit(num: int) -> int:
    pass

assert single_digit(5665) == 5
assert single_digit(123456789) == 1
def single_digit(num: int) -> int:
    sum = bin(int(num))[2:].count("1")
    while int(sum)>=10:
        sum=bin(int(sum))[2:].count("1")
    return sum
def single_digit(num: int) -> int:
    while True:
        num = bin(num)[2:].count('1')
        if num < 10:
            return num

assert single_digit(5665) == 5
assert single_digit(123456789) == 1
assert single_digit(1) == 1

最近都是简单难度的题呢

 public Integer singleDigit(Integer integer) {
        do {
            String s = Integer.toBinaryString(integer);
            String[] split = s.split("");
            integer = Math.toIntExact(Arrays.asList(split).stream().map(Integer::valueOf).filter(b -> b != 0).count());
        }
        while (integer > 10);
        return integer;
    }

    @Test
    public void testSingleDigit() {
        assert singleDigit(123456789).equals(1);
        assert singleDigit(5665).equals(5);
        assert singleDigit(1).equals(1);
    }
def  single_digit(num: int) -> int:
    while(True):
        bbb = bin(num).replace("0b","")
        # 查bbb里有多少个1
        length = len(bbb.replace("0",""))
        if length<10:
            return length
        else:
            num=length
    return length

def test_single_digit():
    assert single_digit(5665) == 5
    assert single_digit(123456789) == 1

参考题解:

def single_digit(num: int) -> int:

    binary_num = '{:b}'.format(num)

    while True:
        total = sum([int(x) for x in binary_num])

        if len(str(total)) > 1:
            binary_num = '{:b}'.format(total)
            continue

        return total

assert single_digit(5665) == 5
assert single_digit(123456789) == 1

思路:while循环。首先将十进制数字转成二进制形式,然后求和,如果非个位数则继续执行前面的动作。

参考题解:

def single_digit(num: int) -> int:

    # 递归函数
    def rec(n: int) -> int:
        total = sum([int(x) for x in '{:b}'.format(n)])
        return total if len(str(total)) == 1 else rec(total)

    return rec(num)

assert single_digit(5665) == 5
assert single_digit(123456789) == 1

思路:使用递归思想。按照需求,第一步将十进制数字转成二进制形式。第二步进行汇总求和得到total,判断total是否是个位数。如果是,则返回;否则继续调用自身,直到最终得到个位数再返回。

def single_digit(num: int) -> int:
    sum = bin(int(num)).replace('0b','').count('1')
    while int(sum) >= 10:
        sum = bin(int(sum))[2:].replace('0b','').count('1')
    return sum

assert single_digit(5665) == 5
assert single_digit(123456789) == 1
def single_digit(num: int) -> int:
    count = sum([int(i) for i in (str(bin(num).replace('0b', '')))])
    if count <= 9:
        return count
    return single_digit(count)


assert single_digit(5665) == 5
assert single_digit(123456789) == 1
关闭