算法Java(递归):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ff(n);
}
private static void ff(int n) {
int[] a = {n/1000,n/100%10,n/10%10,n%10};
int b = 0;
int s = 0;
if(a[0]==a[1]&&a[1]==a[2]&&a[2]==a[3])
System.out.println(""+a[0]+a[1]+a[2]+a[3]+" - "+a[3]+a[2]+a[1]+a[0]+" = "+"0000");
else {
for (int i = 0; i < 4; i++) {
for (int j = i+1; j < 4; j++) {
if(a[i]<a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
b = a[0]*1000+a[1]*100+a[2]*10+a[3];
s = a[3]*1000+a[2]*100+a[1]*10+a[0];
int cha = b-s;
System.out.println(""+a[0]+a[1]+a[2]+a[3]+" - "+a[3]+a[2]+a[1]+a[0]+" = "+cha);
if(cha!= 6174)
ff(b-s);
}
}
}