Mysterious number 6174 [Kaprekar Theorem] in Java : <p>In 1949 the mathematician D. R. Kaprekar, devised a process now known as Kaprekar's operation. First choose a four digit number where the digits are not all the same (that is not 1111, 2222,...). Then rearrange the digits to get the largest and smallest numbers these digits can make. Finally, subtract the smallest number from the largest to get a new number, and carry on repeating the operation for each new number.</p>

<blockquote>
  <p>Let's try it out, starting with the number 2005, the digits of last
  year. The maximum number we can make with these digits is 5200, and
  the minimum is 0025 or 25 (if one or more of the digits is zero, embed
  these in the left hand side of the minimum number)</p>
</blockquote>

<pre><code>5200 - 0025 = 5175
7551 - 1557 = 5994
9954 - 4599 = 5355
5553 - 3555 = 1998
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
</code></pre>

<p>Now Objective is verify this theorem &amp; find the number of iteration take to reach 6174.</p>

<blockquote>
  <p><strong>Can anyone give a better algorithm?</strong>  Here is my code.</p>
</blockquote>

<pre><code>public int VerifyKaprekarTheorem(int m) {
    if (m &lt;= 1000 || m &gt; 9999) {
        return -1;
    }
    String orginal = String.valueOf(m);
    int count = 0;
    while (true) {
        int Max = Integer.parseInt(sortString(orginal, false));
        int Min = Integer.parseInt(sortString(orginal, true));
        count++;
        int diff = Max - Min;
        if (diff == 6174) {
            break;
        }
        orginal = String.valueOf(diff);
    }
    return count;
}

public static String sortString(String Source, boolean assendingOrder) {
    char[] original = String.valueOf(Source).toCharArray();
    Arrays.sort(original);
    if (assendingOrder) {
        return new String(original);
    }
    char[] dessending = new char[original.length];
    for (int i = original.length - 1; i &gt;= 0; i--) {
        dessending[i] = original[(original.length - 1) - i];
    }
    return new String(dessending);
}
</code></pre>

<blockquote>
  <p>and testcase</p>
</blockquote>

<pre><code>public void testCase01() {
    int actual = VerifyKaprekarTheorem(4321);   
    assertEquals(3, actual);
}
</code></pre>
