數字黑洞

在這裏插入圖片描述
在這裏插入圖片描述
這對這道題,因爲我們不知道,要進行多少次差,才能得到6174,因此我們需要用一個死循環或者遞歸來寫。知道滿足條件再退出。這裏我用遞歸來寫。
處理數據注意:
因爲數字中含有0,輸出的時候,我們需要把這個0也輸出,因此,我們需要把數字拼接成字符串,然後用內置函數Integer.valueOf轉化爲數字做差。滿足要求,輸出這個字符串即可。
特殊情況:如果數字全部一樣。直接原樣輸出,並且等於 “0000”。
下面看代碼:

import java.util.Arrays;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {	
		int num = new Scanner(System.in).nextInt();
		show(processData(num));
	}
	public static void show(int [] num) {
		int max, min,differ;
		String increase = "", decrement = "";
		for(int i = 0; i < num.length; i++) {
			increase  += num[i];
			decrement += num[3 - i];
		}
		max = Integer.valueOf(decrement);
		min = Integer.valueOf(increase);
		differ = max - min;
		if(differ == 0) {
			System.out.println(decrement + " - " + increase + " = 0000");
			return ;
		}
		System.out.println(decrement + " - " + increase + " = " + differ);
		if(differ == 6174) {
			return ;
		}
		show(processData(differ));
	}
	public static int [] processData(int num) {
		int [] data = new int [4];
		for(int i = 0; i < 4; i++) {
			data[i] = num % 10;
			num /= 10;
		}
		Arrays.sort(data);
		return data;
	}
}

測試數據:
在這裏插入圖片描述
輸入數據:
6767
輸出數據:
6767
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章