题目
思路
水题,利用sprintf和sscanf进行字符串和整数的格式转换
代码
#include <iostream>
#include<algorithm>
using namespace std;
bool cmp(char a, char b) {
return a > b;
}
int main() {
int n;
cin >> n;
char num[5];
sprintf_s(num, "%04d", n);
int k = num[0];
bool bd = false;
for (int i = 1; i < 4; ++i) {
if (num[i] != k) {
bd = true;
break;
}
}
if (!bd) {
cout << num << " - " << num << " = 0000";
return 0;
}
int ans = 0;
while (ans != 6174) {
int num1, num2;
sort(num,num+4);
sscanf_s(num, "%04d", &num1);
sort(num,num+4,cmp);
sscanf_s(num, "%04d", &num2);
ans = num2 - num1;
printf("%04d - %04d = %04d\n", num2, num1, ans);
sprintf_s(num, "%04d", ans);
}
return 0;
}