Java Program to Break an Integer into Digits
Breaking an integer into digits means separating a number such as 2876 into 2, 8, 7 and 6. It is the first step in many number programs, such as summing digits, reversing a number, or checking Armstrong and palindrome numbers.
Two operators do all the work:
number % 10gives the last digit (2876 % 10 = 6),number / 10removes the last digit (2876 / 10 = 287).
1. Extract Digits Using % and /
The loop repeats the two steps until the number becomes 0. Because the last digit comes out first, the digits are printed from right to left. The program also adds them up to show the sum of digits.
import java.util.Scanner;
public class BreakIntoDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
int temp = Math.abs(number);
int position = 1;
int sum = 0;
while (temp > 0) {
int digit = temp % 10;
System.out.println("Digit " + position + " from the right: " + digit);
sum += digit;
temp /= 10;
position++;
}
System.out.println("Sum of digits: " + sum);
}
}
Enter a number: 2876313 Digit 1 from the right: 3 Digit 2 from the right: 1 Digit 3 from the right: 3 Digit 4 from the right: 6 Digit 5 from the right: 7 Digit 6 from the right: 8 Digit 7 from the right: 2 Sum of digits: 30
2. Store the Digits in an Array in the Original Order
To keep the digits left to right, first count them, then fill the array from the last position to the first.
import java.util.Arrays;
public class DigitsToArray {
public static void main(String[] args) {
int number = 24680;
int count = String.valueOf(number).length();
int[] digits = new int[count];
int temp = number;
for (int i = count - 1; i >= 0; i--) {
digits[i] = temp % 10;
temp /= 10;
}
System.out.println("Number: " + number);
System.out.println("Digits: " + Arrays.toString(digits));
}
}
Number: 24680 Digits: [2, 4, 6, 8, 0]
3. Break a Number into Digits Using String Methods
Another way is to convert the number to a String and read each character. Character.getNumericValue() turns the character '7' into the number 7.
public class DigitsFromString {
public static void main(String[] args) {
long number = 9081726354L;
String text = String.valueOf(number);
System.out.print("Digits of " + number + ": ");
for (char ch : text.toCharArray()) {
int digit = Character.getNumericValue(ch);
System.out.print(digit + " ");
}
System.out.println();
}
}
Digits of 9081726354: 9 0 8 1 7 2 6 3 5 4
4. Summary
number % 10gives the last digit andnumber / 10removes it.- Repeating those steps in a loop extracts the digits from right to left.
- Fill an array from the end to keep the digits in their original order.
- Converting the number to a string is a simple alternative.