您好,登錄后才能下訂單哦!
給定任一個(gè)各位數(shù)字不完全相同的4位正整數(shù),如果我們先把4個(gè)數(shù)字按非遞增排序,再按非遞減排序,然后用第1個(gè)數(shù)字減第2個(gè)數(shù)字,將得到一個(gè)新的數(shù)字。一直重復(fù)這樣做,我們很快會(huì)停在有“數(shù)字黑洞”之稱的6174,這個(gè)神奇的數(shù)字也叫Kaprekar常數(shù)。
例,我們從6767開始,將得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
現(xiàn)給定任意4位正整數(shù),請(qǐng)編寫程序演示到達(dá)黑洞的過程。
輸入格式:
輸入給出一個(gè)(0, 10000)區(qū)間內(nèi)的正整數(shù)N。
輸出格式:
如果N的4位數(shù)字全相等,則在一行內(nèi)輸出“N - N = 0000”;否則將計(jì)算的每一步在一行內(nèi)輸出,直到6174作為差出現(xiàn),輸出格式見樣例。注意每個(gè)數(shù)字按4位數(shù)格式輸出。
輸入樣例1:
6767
輸出樣例1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
輸入樣例2:
2222
輸出樣例2:
2222 - 2222 = 0000
具體代碼如下:
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int ans = ds(x)-xs(x); if(ans==0){ System.out.printf("%04d - %04d = %04d\n",ds(x),xs(x),ans); }else{ int n ; do{ n = ds(x)-xs(x); System.out.printf("%04d - %04d = %04d\n",ds(x),xs(x),n); x = n; }while(n!=6174); } } public static int ds (int x){ int[]a = new int[4]; a[0] = x/1000; a[1] = x/100%10; a[2] = x/10%10; a[3] = x%10; Arrays.sort(a); int sum = a[3]*1000+a[2]*100+a[1]*10+a[0]; return sum; } public static int xs (int x){ int[]a = new int[4]; a[0] = x/1000; a[1] = x/100%10; a[2] = x/10%10; a[3] = x%10; Arrays.sort(a); int sum = a[0]*1000+a[1]*100+a[2]*10+a[3]; return sum; } }
輸出如下:
4695 9654 - 4569 = 5085 8550 - 0558 = 7992 9972 - 2799 = 7173 7731 - 1377 = 6354 6543 - 3456 = 3087 8730 - 0378 = 8352 8532 - 2358 = 6174
總結(jié)
以上是本文關(guān)于Java編程數(shù)字黑洞的代碼實(shí)現(xiàn),希望對(duì)大家學(xué)習(xí)Java有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。