【每日一题20220624】3 或 5 的倍数

:mage:‍如果我们列出所有小于 10 且是 3 或 5 的倍数的自然数,我们会得到 3、5、6 和 9。这些倍数之和是 23。

设计一个方法,使其返回传入数字以下的所有 3 或 5 的倍数之和。此外,如果数字为负数,则返回 0。

注意:如果数字是 3 和 5 的倍数, 则只计算一次。

【示例】
输入:10
输出:23
解释:列出所有小于 10 且是 3 或 5 的倍数的自然数,我们会得到 3、5、6 和 9。这些倍数之和是 23。

题目难度:简单
题目来源:Multiples of 3 or 5 | Codewars


def solution(number):
    pass

assert solution(10) == 23
assert solution(-1) == 0
assert solution(15) == 45
assert solution(200) == 9168
def solution(number: int) -> int:
    result = 0
    i = 1
    if number < 0:
        return 0
    else:
        while i < number:
            if i % 3 == 0 or i % 5 == 0:
                result += i
            i += 1
        return result


assert solution(10) == 23
assert solution(-1) == 0
assert solution(15) == 45
assert solution(200) == 9168
def solution(number: int) -> int:
    return sum(i for i in range(number) if i % 3 == 0 or i % 5 == 0)
def solution(number):
    return sum([i for i in range(number) if i % 3==0 or i % 5 == 0])

assert solution(10) == 23
assert solution(-1) == 0
assert solution(15) == 45
assert solution(200) == 9168
def solution(number):
    return sum([i for i in range(1, number) if i % 3 == 0 or i % 5 == 0]) if number>0 else 0
def solution(number):
    return sum([i for i in range(1,number) if i%3==0 or i%5==0]) if number>0 else 0

assert solution(10) == 23
assert solution(-1) == 0
assert solution(15) == 45
assert solution(200) == 9168
def solution(number: int)-> int:
    result = [i for i in range(1, number) if i % 3 == 0 or i % 5 == 0]
    result = sum(result)
    return result


if __name__ == '__main__':
    assert solution(10) == 23
    assert solution(-1) == 0
    assert solution(15) == 45
    assert solution(200) == 9168
def solution(number):
    if number < 0:
        return 0
    s = []
    for i in range(1, number):
        if i % 3 == 0 or i % 5 == 0:
            s.append(i)
    return sum(s)
    # return sum([i for i in range(1, number) if (i % 3 == 0 or i % 5 == 0)]) if number > 0 else 0


assert solution(10) == 23
assert solution(-1) == 0
assert solution(15) == 45
assert solution(200) == 9168
def solution(number):
    if number<0:
        return 0
    s=set(i for i in range(3, number,3))
    s.update(set(i for i in range(5, number,5)))
    return sum(s)
关闭