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?
This uses the modulo 10 method to figure out each digit in a number greater than 0, then this will reverse the order of the array. This is assuming you are not using "0" as a starting digit.
This is modified to take in user input. This array is originally inserted backwards, so I had to use the
Collections.reverse()
call to put it back into the user's order.Try this:
You will get first = 1, second = 2, third = 3 and fourth = 4 ....
see bellow my proposal with comments
To do this, you will use the
%
(mod) operator.The mod operator will give you the remainder of doing int division on a number.
So,
Because:
Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.
Code to print the numbers in the correct order:
Easier way I think is to convert the number to string and use
substring
to extract and then convert to integer.Something like this:
ouput is 2014