標籤:pat 演算法 stringstream vector
題目如下:
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 = 10899810 - 0189 = 96219621 - 1269 = 83528532 - 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\n",res.num1,res.num2,input); break; }else{ printf("%04d - %04d = %04d\n",res.num1,res.num2,input); } }while(input != 6174); return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
1069. The Black Hole of Numbers (20)