统计数字2出现的次数 - Python 代码实现
\u003cp\u003e\u003cstrong\u003e问题描述\u003c/strong\u003e\u003cbr\u003e\u003e 统计给定范围[L, R]内所有整数中数字2出现的次数。\u003cbr\u003e\u003e 例如,在范围[2, 22]内,数字2分别在2、12、20、21、22中出现,总共出现了6次。\u003cbr\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003e输入描述\u003c/strong\u003e\u003cbr\u003e\u003e 输入一行,包含两个正整数L和R,用空格隔开,表示范围的起始和结束。\u003cbr\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003e输出描述\u003c/strong\u003e\u003cbr\u003e\u003e 输出一行,表示数字2出现的次数。\u003cbr\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003e样例输入\u003c/strong\u003e\u003cbr\u003e\u003e 2 22\u003cbr\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003e样例输出\u003c/strong\u003e\u003cbr\u003e\u003e 6\u003cbr\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003e代码实现\u003c/strong\u003e\u003cbr\u003e\u003e \u003ccode\u003epython\n# 获取输入的范围\nl, r = map(int, input().split())\n\n# 初始化计数器\ncount = 0\n\n# 遍历范围内的每个数字\nfor num in range(l, r+1):\n # 将数字转换为字符串\n for digit in str(num):\n # 判断字符是否为'2'\n if digit == '2':\n # 如果是,计数器加1\n count += 1\n\n# 输出计数器的值\nprint(count)\n\u003c/code\u003e\u003cbr\u003e\u003c/p\u003e
原文地址: https://www.cveoy.top/t/topic/qiNA 著作权归作者所有。请勿转载和采集!