用 Python 编写程序找出给定范围内特殊数字的数量
pythonserver side programmingprogramming更新于 2026/1/25 20:28:17
假设我们给定一个整数范围,并被要求找出该范围内的特殊数字。特殊数字是正整数,其十进制表示只有 1 位数字。如果数字可以被其十进制表示的数字数量整除,并且商值本身就是一个特殊数字,则十进制表示中有超过 1 位数字的数字也可以是特殊的。我们返回给定范围 (left_limit, right_limit) 中特殊数字的数量。
因此,如果输入为 left_limit = 5, right_limit = 30,则输出将为 13。
此范围内的特殊数字为:5、6、7、8、9、10、12、14、16、18、20、24 和 28。
为了解决这个问题,我们将遵循以下步骤 −
- if right_limit < 10,则
- 返回 right_limit - left_limit + 1
- len_right := (right_limit) 的字符串表示大小
- number_list := [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18]
- 对于范围从 2 到 len_right + 1 的 j,执行
- 对于 number_list 中的每个 k,执行
- temp1 := k * j
- 如果 temp1 的字符串表示大小与 j 相同,则
- 将 temp1 插入到 number_list 的末尾
- 否则当 len(str(temp1)) > j,则
- 退出循环
- 如果number_list[number_list的大小-1] >= right_limit,则
- 退出循环
- 对于 number_list 中的每个 k,执行
- 从 number_list 中删除重复值并排序
- count := 0
- 对于 number_list 中的每个 temp2,执行
- 如果 temp2 >= left_limit 且 temp2 <= right_limit,则
- count := count + 1
- 如果 temp2 >= left_limit 且 temp2 <= right_limit,则
- 返回 count
示例
让我们看看下面的实现以便更好地理解 −
def strange(left_limit, right_limit): if right_limit < 10: return right_limit - left_limit + 1 len_right = len(str(right_limit)) number_list = [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18] for j in range(2, len_right + 1): for k in number_list: temp1 = k*j if len(str(temp1)) == j: number_list.append(temp1) elif len(str(temp1)) > j: break if number_list[len(number_list)-1] >= right_limit: break number_list = list(set(number_list)) count = 0 for temp2 in number_list: if temp2 >= left_limit and temp2 <= right_limit: count = count + 1 return count print(strange(5, 30))
输入
5, 30
输出
13
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

