PAT_A1069
PAT甲级1069.
目录
A1069
题目
样例
样例1
输入:
6767
输出:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
样例2
输入:
2222
输出:
2222 - 2222 = 0000
思路和坑点
对字符串进行升序和降序排列,然后用其相应的数值进行计算,然后按照格式输出结果,直到出现6174.
坑点:
输出的数字不一定是刚好4位的,所以需要先按照数字读入,然后补充成4位的字符串;注意输出格式中的空格个数。
AC代码
#include<bits/stdc++.h>
using namespace std;
int main(void){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
char ch[5];
int n;
scanf("%d",&n); //对于不足四位的整数,要补0
sprintf(ch,"%04d",n);
if(ch[0]==ch[1]&&ch[1]==ch[2]&&ch[2]==ch[3]){ //如果全等,直接输出
printf("%s - %s = 0000",ch,ch);
}
else{
while(1){ //循环处理
int a,b,c; //被减数,减数,差
sort(ch,ch+4); //给字符排序
sscanf(ch,"%d",&b); //读取降序排列的数
reverse(ch,ch+4); //降序逆置后变为升序
sscanf(ch,"%d",&a); //读取升序排列的数
c=a-b; //计算并输出
printf("%04d - %04d = %04d\n",a,b,c);
if(c==6174) break; //如果达到要求,结束循环,否则将字符串置为差继续循环
else sprintf(ch,"%04d",c); //必须保证4位的格式,不够的补0
}
}
return 0;
}