在 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