1069 The Black Hole of Numbers (20 分)字符串数字加减

版权声明:假装这里有个版权声明…… https://blog.csdn.net/CV_Jason/article/details/86064814

题目

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 , 1 0 4 ) (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

解题思路

  题目大意: 给一个数组n,先对各个数字位从大到小排序得到a,然后逆置得到b,计算a-b,得到c,重复上述过程,直到得到6174,或者,对于特例,四个数字位完全相同,那么输出0000。
  解题思路: 直接按照题意计算就好,使用stl::algorithm中的reverse和sort算法,会大大简化这道题的计算过程,另外,使用stringstream和to_string方便string和int之间的转换,string方便数据的表示,int方便数据的计算。

/*
** @Brief:No.1069 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2019-01-08
** @Solution: Accepted!
*/
#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
string a,b;
void digit4(string&c){
	if(c.size()<2){
		c = "000"+c;
	}else if(c.size()<3){
		c = "00" + c;
	}else if(c.size()<4){
		c = "0" + c;
	}
}
string sub(){
	int num_a,num_b,num_c;
	string c;
	stringstream ss1,ss2;
	ss1<<a;
	ss1>>num_a;
	ss2<<b;
	ss2>>num_b;
	//cout<<"num_a = "<<num_a<<" num_b = "<<num_b<<endl;
	num_c = num_a - num_b;
	c = to_string(num_c);
	digit4(c);
	return c;
}
int main(){
	string n;
	while(cin>>n){
		digit4(n);
		do{
			sort(n.begin(),n.end(),[](char a,char b){return a>b;});
			a = n;
			reverse(n.begin(),n.end());
			b = n;
			n = sub();
			cout<<a<<" - "<<b<<" = "<<n<<endl;
		}while(n!="0000"&&n!="6174");
	}
	return 0;
} 

在这里插入图片描述

总结

  这道题没什么难的,PAT乙级1019和这道题一模一样,这道题不过是其英文翻版罢了。

猜你喜欢

转载自blog.csdn.net/CV_Jason/article/details/86064814