PAT乙级篇之数字黑洞

原题:
给定任一个各位数字不完全相同的4位正整数,如果我们先把4个数字按非递增排序,再按非递减排序,然后用第1个数字减第2个数字,将得到
一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的6174,这个神奇的数字也叫Kaprekar常数。

例如,我们从6767开始,将得到

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
… …

现给定任意4位正整数,请编写程序演示到达黑洞的过程

题解:
python

s=input()
s+=‘0’*(4-len(s))
while True:
b=’’.join(sorted(list(s)))
a=b[::-1]
s=str(int(a)-int(b)) if int(a)-int(b) else None
print("{} - {} = {}".format(a,b,s or ‘0000’))
if s==‘6174’ or not s:
break

猜你喜欢

转载自blog.csdn.net/weixin_44482648/article/details/86477698