【每日一题20220323】统计数字

:mage:‍给定一个正整数n和一个目标数字target,请编写一个函数,将0到n之间(包含首尾)的所有数字进行平方,统计并返回这些平方数中包含target目标数的总个数。如果平方数中含出现多次目标数字,应当统计多次。

示例:
输入:n=10, target = 1
输出:4
解释:平方后得到 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100,含有1的数字有1,16,81和100,所以是返回4。

题目难度:简单
题目来源:CodeWars:Count the Digit

def solution(n: int, target: int) -> int:
    # your code here

assert solution(10, 1) == 4
assert solution(25, 1) == 11
assert solution(5750, 0) == 4700
assert solution(12224, 8) == 7733
def solution(n: int, target: int) -> int:
    return ''.join([str(i**2) for i in range(n + 1)]).count(str(target))
def solution(n: int, target: int) -> int:
    return ''.join([str(i ** 2) for i in range(n + 1)]).count(str(target))


assert solution(10, 1) == 4
assert solution(25, 1) == 11
assert solution(5750, 0) == 4700
assert solution(12224, 8) == 7733

有点不理解,按照题目的意思,是平方后所得的数字的中含有1的,solution(25, 1)是不是应该只有10个呢
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625]
10个有1,16,81,100,121,144,169,196,361,441


def count_num(n:int,target:int)->int:
    list_1=[i**2 for i in range(0,n+1)]
    list_2=[i for i in list_1 if str(target) in str(i)]
    return len(list_2)

实际统计的是所有数平方出现1的次数,121出现两次1,算两次

是的 对对,谢谢哈

def solution(n: int, target: int) -> int:
    return ''.join([str(i ** 2) for i in range(n + 1)]).count(str(target))


assert solution(10, 1) == 4
assert solution(25, 1) == 11
assert solution(5750, 0) == 4700
assert solution(12224, 8) == 7733

:grinning: :grinning: :grinning:

def solution(n: int, target: int) -> int:
   return ''.join([str(i*i) for i in range(n+1)]).count(str(target))
    def solution(n: int, target: int) -> int:
        return len(''.join([str(i**2) for i in range(n+1)]).split(str(target))) - 1
def solution(n: int, target: int) -> int:
    # your code here
    ls = [ str(i**2).count(str(target)) for i in  range(n+1) if str(target) in str(i**2)]
    return sum(ls)

if __name__ == '__main__':

    assert solution(10, 1) == 4
    assert solution(25, 1) == 11
    assert solution(5750, 0) == 4700
    assert solution(12224, 8) == 7733
def solution(n: int, target: int) -> int:
    pf_list = [i*i for i in range(n + 1)]

    count = 0
    for num in pf_list:
        c = str(num).count(str(target))
        count += c
    return count
关闭