6174


I recently saw a Numberphile video about Kaprekar's constant. Kaprekar, an Indian mathematician defined a very simple yet very interesting iterative operation on a four digit number (with at least one distinct digit) which would always result in a constant (6174). It truly brings out the beauty in mathematics. 
This app takes a four digit number input and goes through the intermediary steps to finally output the constant.
The most significant part of the project was figure out an implementation to keep track of the leading zeros. It was a fun little friday night coding project. The workings of the operation is described in the following picture.



The algorithm:

// ......................... //
while (!number.equals("6174")) {
 ascending = ascending(number);
 decending = reverse(ascending);
 difference = Integer.parseInt(decending) - Integer.parseInt(ascending);
 String format = String.format("%%0%dd", 4);
 differenceString = String.format(format, difference);
 result = result + (count + ". " + (decending) + " - " + (ascending) + " = " + (differenceString) + "\n");
 count++;
 number = differenceString;
}
// ......................... //

Functions:


public static String ascending(String number) {
 char[] asc = number.toCharArray();
 Arrays.sort(asc);
 return (new String(asc));
}

public static String reverse(String ascendingNumber) {
 return (new StringBuilder(new String(ascendingNumber)).reverse().toString());
}

public static boolean valid(String number) {
 if (number.equals("")) {
  return false;
 }
 return (!(Integer.parseInt(number) % 1111 == 0) && number.length() == 4);
}