Separate Digits From Integer

Sometimes in programming problems we need to split a number into single digits, there are several ways to accomplish this, and in this post we will see two of them.

In this first approach we will transform the number into a String and then we will iterate through every character from the String and transform that character into an integer.

public static void usingString(int number){
    String string = number + "";
        for(int i = string.length() - 1; i >= 0; i--){
            int digit = string.charAt(i) - '0';
            System.out.print(digit);
        }
}

But there’s another way, which doesn’t need to convert the number to a String and it’s accomplish by using the modulo operation.

public static void usingMod(int number){
    int digit = 0;
    while(number != 0){
        digit = number % 10;
        number = number / 10;
        System.out.print(digit);
    }
}

This works by extracting the last digit with the modulo operation and shrinking the original number by dividing it by 10 to get the next digit.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s