题目
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in nonincreasing 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, 10000).
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 diference. 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位的整数N,对N降序排列-对N升序排列=下一次的整数N,循环处理直到N=6174为止,打印其处理过程(特殊情况:如果N的4位数字相同,打印并退出处理)
解题思路
- 用字符串接收整数s,并用0左边补齐整数到4位
- a=s,b=s,a降序排列后转为数字an,b升序排列转为数字bn
- bn-an即为下次处理的整数
易错点
- 若输入的数字为6174,需要打印7641 - 1467 = 6174(否则测试点5错误)(建议使用do...while可以省去针对开始输入为6174的单独处理)
知识点
- 字符串中字符排序
sort(s.begin(),s.end(),cmp);
- 利用字符串操作对齐整数
2.1 右对齐。如:4位对齐,输入1,要求得到"0001";输入11,要求得到"0011"s.insert(0,4-s.length,'0');
2.2 左对齐。4位对齐,输入1,要求得到"1000",输入11,要求得到"1100"s.insert(s.length,4-s.length,'0');
Code
Code 01
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(char a, char b) {
return a>b;
}
int main(int argc, char * argv[]) {
string s,a,b;
cin>>s;
s.insert(0,4-s.length(),'0');
do {
a=s,b=s;
sort(a.begin(),a.end(),cmp);
sort(b.begin(),b.end());
int res = stoi(a)-stoi(b);
s=to_string(res);
s.insert(0,4-s.length(),'0');
cout<<a<<" - "<<b<<" = "<<s<<endl;
} while(s!="6174"&&s!="0000");
return 0;
}