在 Python 中检查大数的任何排列是否能被 8 整除
假设,我们得到一个很大的数字,并且我们需要找出该数字的任何数字排列是否能被 8 整除。该数字以字符串格式提供给我们。
因此,如果输入类似于:input_num = 4696984,则输出将为“能被八整除”。
为了解决这个问题,我们将检查数字的所有可能的三位数排列,并查看它们是否可以出现在数字的任何全数字排列中。如果一个能被八整除的三位数排列出现在数字的全数字排列的末尾,我们将说该排列能被 8 整除。
为了解决这个问题,我们将遵循以下步骤:
- 如果 input_num 的长度 < 3,则
- 如果 input_num 模 8 等于 0,则
- 返回 True
- input_num := input_num 的反转
- 如果 input_num 模 8 等于 0,则
- 返回 True
- 返回 False
- 如果 input_num 模 8 等于 0,则
- temp_arr := 一个大小为 10 的新列表,初始化为 0。
- 对于从 0 到 input_num 大小的范围内的计数,执行以下操作:
- temp_arr[input_num[count] - 0] := temp_arr[input_num[count] - 0] + 1
- 对于从 104 到 999 的范围内的计数,以 8 为步长递增,执行以下操作:
- temp := count
- occurences := 一个大小为 10 的新列表,初始化为 0。
- occurences[temp 模 10] := occurences[temp 模 10] + 1
- temp := temp / 10
- occurences[temp 模 10] := occurences[temp 模 10] + 1
- temp := temp / 10
- occurences[temp 模 10] := occurences[temp 模 10] + 1
- temp := count
- 如果 occurences[temp 模 10] > temp_arr[temp 模 10],则
- 进行下一次迭代
- temp := temp / 10
- 如果 occurences[temp 模 10] > temp_arr[temp 模 10],则
- 进行下一次迭代
- temp := temp / 10
- 如果 occurences[temp 模 10] > temp_arr[temp 模 10],则
- 进行下一次迭代
- 返回 True
- 返回 False
让我们看看以下实现以更好地理解:
示例
def solve(input_num):
if len(input_num) < 3:
if int(input_num) % 8 == 0:
return True
input_num = input_num[::-1]
if int(input_num) % 8 == 0:
return True
return False
temp_arr = 10 * [0]
for count in range(0, len(input_num)):
temp_arr[int(input_num[count]) - 0] += 1
for count in range(104, 1000, 8):
temp = count
occurences = 10 * [0]
occurences[int(temp % 10)] += 1
temp = temp / 10
occurences[int(temp % 10)] += 1
temp = temp / 10
occurences[int(temp % 10)] += 1
temp = count
if (occurences[int(temp % 10)] >
temp_arr[int(temp % 10)]):
continue
temp = temp / 10
if (occurences[int(temp % 10)] >
temp_arr[int(temp % 10)]):
continue
temp = temp / 10
if (occurences[int(temp % 10)] >
temp_arr[int(temp % 10)]):
continue
return True
return False
if solve("4696984"):
print("Divisible by eight")
else:
print("Not divisible by eight")输入
4696984
输出
Divisible by eight
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP