PTA 7-2 数字之王 (20 分)

题目

给定两个正整数 N
1

<N
2

。把从 N
1

到 N
2

的每个数的各位数的立方相乘,再将结果的各位数求和,得到一批新的数字,再对这批新的数字重复上述操作,直到所有数字都是 1 位数为止。这时哪个数字最多,哪个就是“数字之王”。

例如 N
1

=1 和 N
2

=10 时,第一轮操作后得到 { 1, 8, 9, 10, 8, 9, 10, 8, 18, 0 };第二轮操作后得到 { 1, 8, 18, 0, 8, 18, 0, 8, 8, 0 };第三轮操作后得到 { 1, 8, 8, 0, 8, 8, 0, 8, 8, 0 }。所以数字之王就是 8。

本题就请你对任意给定的 N
1

<N
2

求出对应的数字之王。

输入格式:
输入在第一行中给出两个正整数 0<N
1

<N
2

≤10
3
,其间以空格分隔。

输出格式:
首先在一行中输出数字之王的出现次数,随后第二行输出数字之王。例如对输入 1 10 就应该在两行中先后输出 6 和 8。如果有并列的数字之王,则按递增序输出。数字间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:
10 14
结尾无空行
输出样例:
2
0 8
结尾无空行

解题思路

start,end = map(int,input().split())
# start,end = map(int,"10 14".split())
# start,end = map(int,"1 10".split())

inputList = [str(i) for i in range(start, end+1)]

def actionRes(a:str) -> str:
    res = 1
    for i in a:
        res = res *(int(i)**3)
    b = str(res)
    resb = 0
    for j in b:
        resb += int(j)
    return str(resb)

def sumLength(list:[str])->int:
    res = 0
    for i in list:
        res += len(i)
    return res

while sumLength(inputList) != len(inputList):
    for index,val in enumerate(inputList):
        inputList[index] = actionRes(val)
    # print(inputList)
from collections import Counter
res = Counter(inputList).most_common()
if len(res) == 0:
    print("")
else:
    resOutput = [int(x) for x,y in res if y == res[0][1]]
    resOutput.sort()
    print(res[0][1])
    resOutput = [str(x) for x in resOutput]
    print(" ".join(resOutput))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章