how to extract digits from a number in java

w‮‬ww.lautturi.com
how to extract digits from a number in java

To extract the digits from a number in Java, you can use the String class's split() method to split the number into individual characters and then convert each character to an integer using the Integer.parseInt() method.

Here's an example of how to extract the digits from a number in Java:

int number = 12345;

// Convert the number to a string
String numberString = String.valueOf(number);

// Split the string into individual characters
String[] digits = numberString.split("");

// Convert the characters to integers
int[] intArray = new int[digits.length];
for (int i = 0; i < digits.length; i++) {
  intArray[i] = Integer.parseInt(digits[i]);
}

// Print the digits
for (int digit : intArray) {
  System.out.println(digit);
}

In the above example, the String.valueOf() method is used to convert the number integer to a string. The split() method is then used to split the string into an array of characters. Finally, a loop is used to convert each character to an integer and store it in an int array.

Alternatively, you can use the % and / operators to extract the digits from a number. Here's an example of how to extract the digits from a number using the % and / operators:

int number = 12345;

while (number > 0) {
  int digit = number % 10;  // Extract the least significant digit
  System.out.println(digit);
  number /= 10;  // Remove the extracted digit from the number
}

In the above example, the % operator is used to extract the least significant digit of the number, and the / operator is used to remove the extracted digit from the number. This is done in a loop until the number is greater than 0.

Created Time:2017-11-01 20:42:51  Author:lautturi