PAT-A-1069 The Black Hole of Numbers 【验证】
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174
-- the black hole of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767
, we'll get:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0,104).
Output Specification:
If all the 4 digits of N are the same, print in one line the equation N - N = 0000
. Else print each step of calculation in a line until 6174
comes out as the difference. All the numbers must be printed as 4-digit numbers.
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
说实话,有点坑,说好了的给四位数,结果测试案例竟然有不够四位的,这个注意一点,不足补零
还有就是 输出一定要是4位数,%04d格式输出
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
int main(){
string data;
cin>>data;
char c=data[0];
if(data[1]==c&&data[2]==c&&data[3]==c){
printf("%s - %s = 0000\n",data.c_str(),data.c_str()); //四位相同情况
return 0;
}
vector<int> stu;
int size=data.size();
for(int i=0;i<size;i++){
stu.push_back(data[i]-'0'); //添加数据
}
for(int l=0;l<4-size;l++){
stu.push_back(0); //不足四位补零
}
int big,small;
while(true){
big=0,small=0;
sort(stu.begin(),stu.end()); //排序
small=stu[0]*1000+stu[1]*100+stu[2]*10+stu[3];
big =stu[3]*1000+stu[2]*100+stu[1]*10+stu[0];
int temp=big-small;
printf("%d - %04d = %04d\n",big,small,temp);
if(temp==6174) break;
stu.clear();
while(temp/10){ //重置数据
stu.push_back(temp%10);
temp/=10;
}
stu.push_back(temp);
while(stu.size()!=4){ //不足补零
stu.push_back(0);
}
}
return 0;
}
上一篇: spring cloud(七) 均衡负载
下一篇: 求两个递增数组的中位数
推荐阅读
-
1069 The Black Hole of Numbers (20分)
-
1069 The Black Hole of Numbers (20 分)(模拟)
-
【PAT】A1069 The Black Hole of Numbers (20分)
-
PAT(A)1069 The Black Hole of Numbers (20分)
-
pat-1069 The Black Hole of Numbers (20分)
-
[PAT-A 1069]The Black Hole of Numbers
-
PAT-A-1069 The Black Hole of Numbers 【验证】
-
PAT A1069 The Black Hole of Numbers (20分)