2

I want to know how to extract digits from a number.

The only method I can think of is converting the number to a string, then use substring() - THEN convert back to int.

Would there be a more efficient way, such that it obtains a specific number like the substring() method, but for an int or a BigInteger?

Topstar
  • 41
  • 5
  • See: http://stackoverflow.com/questions/3389264/how-to-get-the-separate-digits-of-an-int-number – Kevin Bowersox Dec 03 '13 at 01:17
  • I would say that using the `substring` method would be the most *efficient*. However, you could do as these answers suggest and use the mod function or divide the number into its individual placeholder values. – Michael Yaworski Dec 03 '13 at 01:29

3 Answers3

2

To understand how to do it, consider this:

  • To remove all digits prior to digit k (counting from the back of the number), compute x % pow(10, k+1)
  • To truncate the last k digits of a number compute x / pow(10, k)

Now you can construct a method that removes the initial part and drops the ending part as needed to compute a substring. Note that the same trick can be applied to numeric representations other than decimal by substituting 10 with the base of the number (i.e. 2 for binary numbers, 16 for hex numbers, and so on).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you for this answer. Perhaps I was unclear with my question, but this was the sort I was looking for. – Topstar Dec 03 '13 at 01:30
2

If you are referring to extracting 1, 2, 3, 4 from 1234, you can use the modulo operator % as follows:

int i = 1234;
while (i > 0) {
    System.out.println(i % 10);
    i = i / 10;
}

this would print 4, 3, 2, 1. To get them in reverse order, you can use a stack to push the values and the pop them.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
0

What you want to do is something like this:

int current = number; 
do {
  System.out.println((current % 10));
  current = current / 10;
} while (currrent > 0);
dimoniy
  • 5,820
  • 2
  • 24
  • 22