0

Question of Java

anybody know?How to transform a number (for example: n = 12345) to the massive of numbers {1,2,3,4,5}.

31st Aug 2017, 3:55 AM
Женя Сторожев
Женя Сторожев - avatar
5 ответов
+ 8
You could also take the last digit with: myNum % 10, then divide the number by 10, until it's zero. Adding the last digit to the end of the array each time. Probably better than converting to String.
31st Aug 2017, 5:50 AM
Rrestoring faith
Rrestoring faith - avatar
+ 6
Here's a way you can do it without converting the number into a string: public class Program { public static void main(String[] args) { int number = 123456789; int[] arr = new int[getNumberOfDigits(number)]; for(int i = arr.length - 1; i >= 0; --i) { arr[i] = number % 10; number /= 10; } for(int num: arr) { System.out.println(num); } } static int getNumberOfDigits(int number) { int length = 1; while((number /= 10) != 0){ ++length; } return length; } }
31st Aug 2017, 6:38 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Empty, thank you 👍👌
31st Aug 2017, 4:53 AM
Женя Сторожев
Женя Сторожев - avatar
+ 1
ChaoticDawg Thank you. 👌💪
31st Aug 2017, 6:38 AM
Женя Сторожев
Женя Сторожев - avatar
0
Ace thank you for your answer. I also thinked.but how to do in the java code?
31st Aug 2017, 4:02 AM
Женя Сторожев
Женя Сторожев - avatar