Option with a preliminary count of the number of digits. Counting the number here is conditional, because in fact it is calculated from which divider to begin to divide the number.
Scanner s = new Scanner(System.in); int a = s.nextInt(); int divider = 1; while (divider <= a) { divider *= 10; } divider /= 10; while (divider > 0) { int digit = a / divider; a -= digit * divider; System.out.print(digit + " "); divider /= 10; }
This option only works with positive numbers.
Option without preliminary counting the number of users and with enumeration of all options for the divisor:
Scanner s = new Scanner(System.in); int a = s.nextInt(); boolean gotFirstDigit = false; for (int divider = 1000 * 1000 * 1000; divider > 0; divider /= 10) { int digit = a / divider; if (!gotFirstDigit) { gotFirstDigit = (digit != 0); } if (gotFirstDigit) { a -= digit * divider; System.out.print(digit + " "); } }
This option also works with positive numbers only.
Both options use the same way to get numbers: the integer part of dividing a number by a given divisor.
To handle zero and negative numbers, you can add the following code:
int a = s.nextInt(); if (a == 0) { System.out.print(0); return; } if (a < 0) { System.out.print("- "); a *= -1; }
The only restriction is that this code will not work for Integer.MIN_VALUE ( -2147483648 ).
1 2 3 4 5 6this is for what input value? - default locale