附上Java实现代码。
1 package NetEasy; 2 3 /** 4 * 数字黑洞 5 */ 6 7 import java.util.Scanner; 8 9 public class NumBlackHole { 10 11 public static void main(String[] args) { 12 Scanner in = new Scanner(System.in); 13 String number = in.next(); 14 // StringBuffer numStr = new StringBuffer(); 15 // numStr.append(number); 16 if(number.charAt(0)==number.charAt(1) && 17 number.charAt(0)==number.charAt(2)&& 18 number.charAt(0)==number.charAt(3)) 19 System.out.println(number+" - "+number+" = 0"); 20 else{ 21 boolean flag = true; 22 // int num = Integer.valueOf(number); 23 while(flag){ 24 number = computeNum(number); 25 if(number.equals("6174")) 26 flag = false; 27 } 28 } 29 30 } 31 32 private static String computeNum(String number) { 33 // String number = Integer.valueOf(num).toString(); 34 StringBuffer numOrder = new StringBuffer(number); 35 for(int i = 0; i < 4; i++){ 36 for(int j = i; j < 4; j++){ 37 if(numOrder.charAt(i) < numOrder.charAt(j)){ 38 char temp = numOrder.charAt(i); 39 numOrder.setCharAt(i, number.charAt(j)); 40 numOrder.setCharAt(j, temp); 41 } 42 } 43 } 44 // StringBuffer numUpper = numOrder; //这样复制,后面numOrder反转了 numUpper会跟着变化 45 String numUpper = numOrder.toString(); 46 String numLower = numOrder.reverse().toString(); 47 int n = Integer.valueOf(numUpper)-Integer.valueOf(numLower); 48 StringBuffer result = new StringBuffer(Integer.valueOf(n).toString()); 49 if(result.length() == 1) 50 result.insert(0, "000"); 51 if(result.length() == 2) 52 result.insert(0, "00"); 53 if(result.length() == 3) 54 result.insert(0, "0"); 55 String resultnum = result.toString(); 56 System.out.println(numUpper+" - "+numLower+" = "+ resultnum); 57 return resultnum; 58 } 59 60 }
时间: 2024-10-09 23:22:07