Saurabh Khare - 9 months ago 83

Java Question

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.

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)

`5200 - 0025 = 5175`

7551 - 1557 = 5994

9954 - 4599 = 5355

5553 - 3555 = 1998

9981 - 1899 = 8082

8820 - 0288 = 8532

8532 - 2358 = 6174

Now Objective is verify this theorem & find the number of iteration take to reach 6174.

Can anyone give a better algorithm?Here is my code.

`public int VerifyKaprekarTheorem(int m) {`

if (m <= 1000 || m > 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 >= 0; i--) {

dessending[i] = original[(original.length - 1) - i];

}

return new String(dessending);

}

and testcase

`public void testCase01() {`

int actual = VerifyKaprekarTheorem(4321);

assertEquals(3, actual);

}

Answer Source

I have change Integer to String then char array than sorting again Integer conversion.

```
public int VerifyKabulekeTheorem(int m) {
if (m <= 1000 || m > 9999) {
return -1;
}
int count = 0;
while (true) {
int Max = largestNumber(m);
int Min = smallestNumber(m);
count++;
m = Max - Min;
if (m == 6174) {
break;
}
}
return count;
}
private static int largestNumber(int i) {
return Integer.parseInt(Arrays.stream((i + "").split("")).sorted((x, y) -> y.compareTo(x))
.collect(Collectors.joining()));
}
private static int smallestNumber(int i) {
return Integer.parseInt(Arrays.stream((i + "").split("")).sorted((x, y) -> x.compareTo(y))
.collect(Collectors.joining()));
}
```