Python程序:在一个给定范围内查找特殊数字的数量
假设我们给定一个整数范围,并要求找出该范围内的特殊数字。特殊数字是指十进制表示中只有一个数字的正整数。十进制表示中有多个数字的数字也可以是特殊的,如果该数字可以被其十进制表示中数字的个数整除,并且商本身也是一个特殊数字。我们返回给定范围 (左边界, 右边界) 内特殊数字的数量。
因此,如果输入类似于左边界 = 5,右边界 = 30,则输出为 13。
此范围内的特殊数字为:5、6、7、8、9、10、12、14、16、18、20、24 和 28。
为了解决这个问题,我们将遵循以下步骤:
- 如果右边界 < 10,则
- 返回右边界 - 左边界 + 1
- 右边界长度 := (右边界) 的字符串表示形式的长度
- 数字列表 := [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18]
- 对于 j 从 2 到 右边界长度 + 1 的范围,执行:
- 对于数字列表中的每个 k,执行:
- temp1 := k * j
- 如果 temp1 的字符串表示形式的长度与 j 相同,则
- 将 temp1 插入数字列表的末尾
- 否则,当 len(str(temp1)) > j 时,则
- 跳出循环
- 如果数字列表[数字列表长度 - 1] >= 右边界,则
- 跳出循环
- 对于数字列表中的每个 k,执行:
- 删除数字列表中的重复值并排序
- 计数 := 0
- 对于数字列表中的每个 temp2,执行:
- 如果 temp2 >= 左边界 且 temp2 <= 右边界,则
- 计数 := 计数 + 1
- 如果 temp2 >= 左边界 且 temp2 <= 右边界,则
- 返回计数
示例
让我们来看下面的实现,以便更好地理解:
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
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
13
广告