1019 数字黑洞 (20分)
程序员文章站
2022-03-13 13:37:17
...
输入样例 1:
6767
输出样例 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
输入样例 2:
2222
解体心得:
- 在初次写str2list时没有考虑到输入是‘123’这样的情形;
# -*- coding: utf-8 -*-
import sys
def str2list(in_str):
result = [c for c in in_str]
result = ['0'] * (4 - len(result)) + result
return result
def kaprekar_process(in_str):
asc_num = sorted(str2list(in_str))
des_num = sorted(asc_num, reverse=True)
difference = int(''.join(des_num)) - int(''.join(asc_num))
while difference != 0 and difference != 6174:
print('%04d - %04d = %04d' % (int(''.join(des_num)), int(''.join(asc_num)), difference))
asc_num = sorted(str2list(str(difference)))
des_num = sorted(asc_num, reverse=True)
difference = int(''.join(des_num)) - int(''.join(asc_num))
print('%04d - %04d = %04d' % (int(''.join(des_num)), int(''.join(asc_num)), difference))
if __name__ == '__main__':
input_str = sys.stdin.readline().strip()
kaprekar_process(input_str)
上一篇: 1019 数字黑洞 (20分)
下一篇: 7-28 黑洞数 (20分)