1.题目详情
试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?例如,在 1 到 11 中,即在 1、2、3、4、5、6、7、8、9、10、11 中,数字 1 出现了 4 次。
2.解题思路
- 利用python中字符串的count方法,统计出现了多少次,注意需先转换为字符串
- 利用for循环遍历,对于for循环中i的每一个值,反复取余,取余后更新i的值再次取余
3.代码实现
#第一种方法,python中count()方法
def jishu(n,x): #x在0-n之间出现了多少次
count = 0
for i in range(1,n+1): #在1-n之间寻找x
x = str(x) #count只支持字符串
count += str(i).count(x)
return count
n,x = map(int,input().split())
# print(n,x)
print(jishu(n,x))
#第二种方法,反复取余
n,x = map(int,input().split())
count = 0
for i in range(1,n+1):
while i > 0:
if i % 10 == x:
count += 1
i = i // 10 #更新i
print(count)
4.知识点
嗯还是统计数字,跟前不久做的题差不多,又是划水的一天
以前写的博客:
数字统计