0
$\begingroup$

All,

Given any number, how can we retrieve each digit of that number?

i.e. For number = 4321, how can I get individual digits 4,3,2 and 1?

  • 1
    How are you given the number? In practice, e.g. in computer science applications, you are sometimes already given the number as a string and you can just extract the characters directly.2010-11-13

3 Answers 3

4

HINT $\rm\displaystyle\quad 3\ =\ \bigg\lfloor \frac{4321}{100}\bigg\rfloor \ mod\ 10 \ =\ 43\ mod\ 10\ \ $ i.e. rightshift then chop off least significant digit.

Or, if you need all digits "unwind" the Horner representation $\rm\ N\ =\ d_0 + 10\ (d_1 + 10\ (d_2 + \:\cdots\: ))\:$ by using division by 10 with remainder, viz $\rm\ d_0 = N\ mod\ 10,\ \ d_1 = (N-d_0)/10\ mod\ 10,\ \ldots$

2

1) Take N modulo 10. 2) Set N = [N/10] ([] is the greatest integer funtion) 3) GO back to step 1) until N = 0.

I hope I haven't misunderstood your question here.

2

For the k'th digit (counting left from the unit's place), divide the number by $10^k$ and call the remainder r. Then, $[r/(10^{k-1})]$ gives the k'th digit.