How to get the separate digits of an int number?

Edy Moore picture Edy Moore · Aug 2, 2010 · Viewed 635k times · Source

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?

Answer

jjnguy picture jjnguy · Aug 2, 2010

To do this, you will use the % (mod) operator.

int number; // = some int

while (number > 0) {
    print( number % 10);
    number = number / 10;
}

The mod operator will give you the remainder of doing int division on a number.

So,

10012 % 10 = 2

Because:

10012 / 10 = 1001, remainder 2

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:

int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
    stack.push( number % 10 );
    number = number / 10;
}

while (!stack.isEmpty()) {
    print(stack.pop());
}