How to split an int number into separate digits?

Last modified date

Comments: 0

How to split an int number into separate digits is a surprisingly common question and there is no native method of doing this in Java.

What we are trying to achieve is given the number 524, how can we split the number into it’s individual digits e.g. 5, 2, 4.

The simplest way of doing this is through using the Mod (Modulus) % operator and then storing the digits in a stack:

The reason we use a stack is because the Mod operation performed in the while loop will actually break up the number in reverse.

So using a stack we can store the last digit at the bottom of the stack so popping the stack will give us the first digit of the number.

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.