分析:
- 把要重排序的数字转成数组
- 对数组进行排序,从小到大排序
- 数组转成字符串,字符串转成数字,得到最小数
- 再把最小数的字符串反转,得到最大数
- 注意:
- 在java语言中,如果使用Arrays.toString(digits);把 int[ ]数组转成字符串,会转成"[0,0,1,1]",而非"0011",出格式异常的错误
package no1_1;
import java.util.*;
import java.io.*;
public class Main {public static void main(String[] args) throws NumberFormatException, IOException {BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));int oldNumber=Integer.parseInt(reader.readLine());while(true) {int newNumber=reOrdering(oldNumber);if(newNumber==oldNumber) {//停止System.out.println(newNumber);break;}else {oldNumber=newNumber;}}}public static int reOrdering(int number) {String s=String.valueOf(number);int[] digits=new int[s.length()];//把整数拆分,存入数组,以便利用数组的Arrays.sort()方法进行排序for(int i=0;i<s.length();i++) {digits[i]=(int)s.charAt(i)-48;//0的ASCII码为48}Arrays.sort(digits);//从小到大排序//如果使用Arrays.toString(digits);把数组转成字符串,会转成"[0,0,1,1]",而非"0011",出格式异常的错误StringBuilder builder=new StringBuilder();for(int digit:digits) {builder.append(digit);}String minString=builder.toString();int min=Integer.parseInt(minString);//最小数StringBuilder reversed=new StringBuilder(minString).reverse();//利用StringBuilder类的reverse()方法反转字符串String maxString=reversed.toString();int max=Integer.parseInt(maxString);//最大数return max-min;}
}