恶心人的点:输入不是四位数,计算结果不是四位数(包括递增序列数不是四位和差值不是四位)
%0xd、sprintf和sscanf是解这道题的利器
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
void newnum(char* num) {
char result[5];
int high, low, def;
sort(num, num + 4);
sscanf(num, "%d", &low);
sort(num, num + 4, cmp);
sscanf(num, "%d", &high);
def = high - low;
sprintf(result, "%04d", def);
printf("%04d - %04d = %04d", high, low, def);
if (def != 6174) {
printf("\n");
newnum(result);
}
}
int main() {
char num[5];
int i;
scanf("%d", &i);
sprintf(num, "%04d", i);
if (num[0] == num[1] && num[0] == num[2] && num[3] == num[0]) {
printf("%s - %s = 0000", num, num);
}else {
newnum(num);
}
return 0;
}