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.html
For example, start from 6767
, we'll get:ios
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.c++
Each input file contains one test case which gives a positive integer N in the range (.git
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.數組
6767
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174
2222
2222 - 2222 = 0000
題意:測試
給一個數組n,先對各個數字位從大到小排序獲得a,而後逆置獲得b,計算a-b,獲得c,重複上述過程,直到獲得6174,或者,對於特例,四個數字位徹底相同,那麼輸出0000。flex
題解:this
剛開始輸入的數字可能不足四位要自動補0 之後的結果可能也不足四位都要自動補0spa
結果是0或者6174都是要退出的.net
一開始沒考慮到6174,測試點5沒過,後來想到了
AC代碼:
#include<iostream> #include<algorithm> using namespace std; int n; int a[10]; int main(){ cin>>n; int big=0; int small=0; int x=n; int k=0,f; if(x==6174){ printf("7641 - 1467 = 6174"); return 0; } while(x!=6174){ k=0; big=0; small=0; while(x>=10){ a[++k]=x%10; x/=10; } a[++k]=x; while(k<4){ a[++k]=0; } sort(a+1,a+1+4); for(int i=1;i<=4;i++){ big=big*10+a[5-i]; small=small*10+a[i]; } x=big-small; printf("%04d - %04d = %04d\n",big,small,x); if(x==0) break; } return 0; }
更簡潔的string處理的代碼:
#include<bits/stdc++.h> using namespace std; bool cmp(char a,char b) { return a>b; } int main(void) { string s; cin>>s; s.insert(0,4-s.size(),'0'); do{ string a=s,b=s; sort(a.begin(),a.end(),cmp); sort(b.begin(),b.end()); int diff=stoi(a)-stoi(b); s=to_string(diff); s.insert(0,4-s.size(),'0'); cout<<a<<" - "<<b<<" = "<<s<<endl; }while(s!="6174"&&s!="0000"); return 0; ———————————————— 版權聲明:本文爲CSDN博主「Imagirl1」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。 原文連接:https://blog.csdn.net/Imagirl1/article/details/82261213