I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
How can I get it in Java?
I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
How can I get it in Java?
Something like this will return the
char[]
:Here is my answer, I did it for myself and I hope it's simple enough for those who don't want to use the String approach or need a more math-y solution:
So I just get the units, print them out, substract them from the number, then divide that number by 10 - which is always without any floating stuff, since units are gone, repeat.
Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.
Edit:
You can convert the character digits into numeric digits, thus:
Without using arrays and Strings . ( digits 1-99999 )
output :
Enter the digit to print separately :- 12345
1 2 3 4 5
Convert it to
String
and useString#toCharArray()
orString#split()
.In case you're already on Java 8 and you happen to want to do some aggregate operations on it afterwards, consider using
String#chars()
to get anIntStream
out of it.Java 8 solution to get digits as int[] from an integer that you have as a String: