1069. The Black Hole of Numbers (20)

题目如下:

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, 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 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


题目要求将一个四位数按照降序、升序生成减数和被减数然后作差,如果差等于0或者6174则停止运算。

题目的注意点在于数字不够4位时要前补0。

为了方便的排序四位数,我们先使用vector容纳四位然后排序,接着利用stringstream将vecotr中元素转成数字,因为输出时减数、被减数和差都需要,因此用一个结构体存储每次的运算结果。

代码如下:

#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <sstream>
#include <stdio.h>

using namespace std;

struct Result{
    int num1;
    int num2;
    int result;
}res;

void compute(int input){
    vector<int> num1,num2;
    num1.push_back(input / 1000);
    num1.push_back(input % 1000 / 100);
    num1.push_back(input % 100 / 10);
    num1.push_back(input % 10);
    num2 = num1;
    sort(num1.begin(),num1.end(),less_equal<int>());
    sort(num2.begin(),num2.end(),greater_equal<int>());
    stringstream ss;
    for(int i = 0; i < 4; i++){
        ss << num1[i];
    }
    int dec1;
    ss >> dec1;
    ss.clear();
    for(int i = 0; i < 4; i++){
        ss << num2[i];
    }
    int dec2;
    ss >> dec2;
    res.num1 = dec2;
    res.num2 = dec1;
    res.result = dec2 - dec1;
}

int main()
{
    int input;
    cin >> input;
    int i = 5;
    do{
        compute(input);
        input = res.result;
        if(input == 0){
            printf("%04d - %04d = %04d
",res.num1,res.num2,input);
            break;
        }else{
            printf("%04d - %04d = %04d
",res.num1,res.num2,input);
        }
    }while(input != 6174);
    return 0;
}


原文地址:https://www.cnblogs.com/aiwz/p/6154083.html