PAT A1069 The Black Hole of Numbers(同B1019)
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
-
思路 1:
模拟,现将数字转化为数组,排序得到升序序列和降序序列,分别转化为整数,做减法,在开始新的一轮循环,直到:出现6174或结果为0; -
code 1:
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int Num[10];
bool cmp(int a, int b){
return a > b;
}
void to_array(int x){
int idex = 0;
do{
Num[idex++] = x % 10;
x /= 10;
}while(x > 0);
}
int to_num(){
int ans = 0;
for(int i = 0; i < 4; ++i){
ans = ans*10 + Num[i];
}
return ans;
}
int main(){
int n, min, max;
scanf("%d", &n);
do{
to_array(n);
sort(Num, Num+4); //升序序列
min = to_num();
sort(Num, Num+4, cmp);
max = to_num();
n = max - min;
printf("%04d - %04d = %04d\n", max, min, n);
}while(n != 0 && n != 6174);
return 0;
}
-
思路2:直接对string排序
-
坑点:
Wrong 1:输入n (0, 104) 可能不足4位
Wrong 2: 输入6174要计算一次,所以要do_whilewhile(s != "0000" && s != "6174");
或者if_break -
T2 code :
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
while(s.size() < 4) s.insert(0, "0"); //Wrong1:n可能不足4位
do{
sort(s.begin(), s.end(), greater<char>());
int a = stoi(s);
sort(s.begin(), s.end());
int b = stoi(s);
int ans = a - b;
printf("%04d - %04d = %04d\n", a, b, ans);
s = to_string(ans);
while(s.size() < 4) s.insert(0, "0");
// if(ans == 0 || ans == 6174) break;
//Wrong2: 输入6174要计算一次,所以要do_while`while(s != "0000" && s != "6174");`或者if_break
}while(s != "0000" && s != "6174");
return 0;
}
- T3 code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
char s[5];
sprintf(s, "%04d", n); //样例2, 3, 4: 输入有可能不足4位
do{
sort(s, s + 4, greater<char>());
int num1 = atoi(s);
printf("%04d - ", num1);
sort(s, s + 4);
int num2 = atoi(s);
printf("%04d = ", num2);
int ans = num1 - num2;
printf("%04d\n", ans);
if(ans == 0) break;
sprintf(s, "%04d", ans);
}while(strcmp(s, "6174") != 0); //样例 5:当输入6174时要计算一次
return 0;
}
- T4 code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
char num[5];
scanf("%d", &n);
sprintf(num, "%04d", n);
while(1)
{
char tmp[5];
strcpy(tmp, num);
sort(num, num+4, greater<char>());
sort(tmp, tmp+4, less<char>());
int ans = atoi(num) - atoi(tmp);
printf("%s - %s = %04d\n", num, tmp, ans);
sprintf(num, "%04d", ans); //必须按4位存入num,否则会运行超时:减成3位时
if(ans == 0 || strcmp(num, "6174") == 0) break;
}
return 0;
}
//样例2,3,4:输入小于1000
//样例 5:6174