Java Program to Extract Digits from A Given Integer
Last Updated :
24 Feb, 2022
Problem Statement: For any random number taken into consideration the goal is to access every digit of the number.
Illustration: Simply taking two numbers be it, 12345 and 110102 absolutely random pick over which computation takes place as illustrated:
Input: 12345
Output: 1 // 1 digit
2 // Digit next to 1st digit
3
4
5 // Last Digit of the number
Input: 110102
Output: 1
1
0
1
0
2
Now, In order to access the digits of a number, there are several approaches ranging from the brute-force approach to the most optimal approach. Two standard approaches are as follows:
Approaches:
Approach 1: Using Integer.toString Method
This method is an inbuilt method present already in the directory of java which returns the string object. This string object is representing the integer value.
Syntax: As it is awarded that Strings are immutable in Java meaning String is a class in java. So,
public static String toString()
The directory in which it is present is as follows:
java.lang.Integer.toString()
Return Method: As seen above in the syntax itself this method returns the string object of the integer value over which it is applied. Also
In this approach we will convert the integer into a string then we will traverse the string.
- Take the integer input.
- Convert the input into string data.
- Traverse through the string and print the character at each position that is the digits of the number.
Below is the implementation of the above approach:
Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
int number = 110102 ;
String string_number = Integer.toString(number);
for ( int i = 0 ; i < string_number.length(); i++) {
System.out.println(string_number.charAt(i));
}
}
}
|
Output:
1
1
0
1
0
2
Approach 2: Using Modulo Operator
Without using inbuilt methods whenever it comes down to extraction of digit straightaway modulo with 10 is the answer because it extracts out the last digit. Similarly, if the process is carried for the number obtained after removing the digit that is already extracted will extract out the last digit from the small number. The same process is iterated till the end is extracted. So,
In this approach, the last digit from the number and then remove it and is carried on till reaching the last digit.
- Take the integer input.
- Finding the last digit of the number.
- Print the last digit obtained and then remove it from the number.
- Keep on following the step 2 and 3 till we reach the last digit.
Below is the implementation of the above approach:
Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
int number = 110102 ;
while (number > 0 ) {
int remainder = number % 10 ;
System.out.println(remainder);
number = number / 10 ;
}
}
}
|
Output:
2
0
1
0
1
1
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...