目录
1,题目描述
Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000
我再补充一个(你懂我意思吧)
Sample Input 3:
6174
Sample Output 3:
7641 - 1467 = 6174
2,思路
关键是如何处理输入的数字,将其按照增序和降序得到num1和num2.
我采用的方法是,将数字按照int类型输入,按照取模除基的方式取出四个数字(若不足四位,此法可直接加0)。调用sort将四个数按升序排序,相应的位乘以相应的基数,即可得到num1和num2;
3,AC代码
#include<bits/stdc++.h>
using namespace std;
int func(int num){
int c[4], num1 = 0, num2 = 0, res, temp = num;
for(int i = 0; i < 4; i++){//i以4为准 可处理0012的情况
c[i] = temp % 10;
temp /= 10;
}
sort(c, c + 4);
num1 = c[3] * 1000 + c[2] * 100 + c[1] * 10 + c[0];
num2 = c[0] * 1000 + c[1] * 100 + c[2] * 10 + c[3];
res = num1 - num2;
if(res != num){
printf("%04d - %04d = %04d\n", num1, num2, res);
return res;
}
return -1;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int num, tem;
cin>>num;
if(num == 6174){
printf("7641 - 1467 = 6174");
return 0;
}
tem = func(num);
while(tem != -1){
tem = func(tem);
}
return 0;
}