输入样例 1:
6767
输出样例 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
输入样例 2:
2222
解体心得:
- 在初次写str2list时没有考虑到输入是‘123’这样的情形;
# -*- coding: utf-8 -*-
import sysdef str2list(in_str):result = [c for c in in_str]result = ['0'] * (4 - len(result)) + resultreturn resultdef 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)