欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PAT-A-1069 The Black Hole of Numbers 【验证】

程序员文章站 2022-07-15 10:53:56
...

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,10​4​​).

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;
}

PAT-A-1069 The Black Hole of Numbers 【验证】