1019 數字黑洞 (20)(20 分)
給定任一個各位數字不完全相同的4位正整數,如果我們先把4個數字按非遞增排序,再按非遞減排序,然後用第1個數字減第2個數字,將得到一個新的數字。一直重複這樣做,我們很快會停在有“數字黑洞”之稱的6174,這個神奇的數字也叫Kaprekar常數。
例如,我們從6767開始,將得到
7766 - 6677 = 1089\ 9810 - 0189 = 9621\ 9621 - 1269 = 8352\ 8532 - 2358 = 6174\ 7641 - 1467 = 6174\ ... ...
現給定任意4位正整數,請編寫程序演示到達黑洞的過程。
輸入格式:
輸入給出一個(0, 10000)區間內的正整數N。
輸出格式:
如果N的4位數字全相等,則在一行內輸出“N - N = 0000”;否則將計算的每一步在一行內輸出,直到6174作爲差出現,輸出格式見樣例。注意每個數字按4位數格式輸出。
輸入樣例1:
6767
輸出樣例1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
輸入樣例2:
2222
輸出樣例2:
2222 - 2222 = 0000
作者: CHEN, Yue
單位: PAT聯盟
時間限制: 100ms
內存限制: 64MB
代碼長度限制: 16KB
package pat_b;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
//牛客網全過,PAT平臺還是有兩個點超時了
public class PAT_B_1019
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String resultStr = in.readLine().trim();
int resultInt = Integer.valueOf(resultStr);//結果數字,默認是輸入的數字
while(true)
{
int[] SmallArray = new int[4];//小數字數組
for(int i = 0; i < 4; i++ )
{
SmallArray[i] = resultInt % 10;
resultInt /= 10;
}
Arrays.sort(SmallArray);
int[] BigArray = new int[4];//大數字數組
for(int i = 0; i< 4; i++)
BigArray[i] = SmallArray[3-i];
int SmallInt = 0;//小數字
for(int i = 0; i < 4; i++)
SmallInt = SmallInt*10 + SmallArray[i];
int BigInt = 0;//大數字
for(int i = 0; i < 4; i++)
BigInt = BigInt*10 + BigArray[i];
resultInt = BigInt - SmallInt;//結果數字
System.out.printf("%04d - %04d = %04d\n",BigInt,SmallInt,resultInt);//格式化輸出
if(resultInt == 0 || resultInt == 6174)//判斷是否爲6174或0(4個數字一樣)。
break;
}
}
}