题目链接
- 对输入的数据进行补全,如果少于4为,则以0在左边补齐
- 采用循环判断每次的结果是否应该停止输出(结果为0或6174则应该停止输出)
c++代码
#include <iostream>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include <algorithm>
using namespace std;
bool cmp(const char& a, const char& b) {
return a > b;
}
int main() {
string s;
int res;
cin >> s;
s.insert(0, 4 - s.length(), '0');
string a, b;
do {
a = s;
b = s;
sort(a.begin(), a.end(), cmp);
sort(b.begin(), b.end());
res = stoi(a) - stoi(b);
s = to_string(res);
s.insert(0, 4 - s.length(), '0');
cout << a << " - " << b << " = " << s << endl;
} while (s != "6174"&s != "0000");
return 0;
}
复制代码
python3代码
def main():
s = '{:0>4}'.format(input())
while True:
str_a = ("".join(sorted(list(s))))
str_b = ("".join(sorted(list(s), reverse=True)))
a = int(str_a)
b = int(str_b)
c = b - a
str_c = '{:0>4}'.format(str(c))
print('{} - {} = {}'.format(str_b,str_a,str_c))
s = str_c
if(c ==0 or c == 6174):
break
main()
复制代码
转载于:https://juejin.im/post/5ce8db99f265da1bb13f0d6e