Generation

generate functionWed, 25 Jan 2023

For a positive integer value of 4 digits or less, consider calculating the difference between the "largest integer value" and the "smallest integer value" that can be obtained by rearranging the numbers of each digit to create the next integer value . For example, the maximum integer value obtained by rearranging the digits of ``5138'' is ``8531'', the minimum integer value is ``1358'', and the difference between them is ``7173''. The next integer value will be "7173". Similarly, in the case of ``21'', the thousands and hundreds digits are considered to be ``0'' (which is ``0021''), and the maximum integer value that can be obtained by rearranging the numbers of each digit is ``2100'', and the smallest The integer value is ``12'' and the difference between them is ``2088'', so the next integer value for ``21'' is ``2088''. For a positive integer value of 4 digits or less, if you repeat the operation to create the next integer value by calculating the difference between the "maximum integer value" and the "minimum integer value" that can be obtained by rearranging the numbers of each digit , always converges to some integer value. Therefore, please create a program that repeats the above calculation and outputs the integer value to the standard output until convergence, when you enter a positive integer value n of 4 digits or less in the command line input.

private static final int NUMBER_OF_DIGITS = 4; public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.close(); int nextNum = n; while (true) { int largestNum = getLargestNum(nextNum); int smallestNum = getSmallestNum(nextNum); nextNum = largestNum - smallestNum; if (nextNum == n) { break; } System.out.println(nextNum); n = nextNum; } System.out.println(n); } private static int getLargestNum(int n) { int[] digits = new int[NUMBER_OF_DIGITS]; for (int i = 0; i < NUMBER_OF_DIGITS; ++i) { int digit = n % 10; digits[i] = digit; n /= 10; }

Questions about programming?Chat with your personal AI assistant