Equation that outputs digit in 1's 10's 100's slot

58 Views Asked by At

I need an equation that outputs the digit in the slot of my choosing

EX1: I want the 10's slot in 1837

EX2: I want the 10's slot in 123456789

EX3: I want the 1000's slot in 93037352

I also need it to be super simple, preferably only using +,-,/,x

1

There are 1 best solutions below

0
On

Not sure if this is the fastest way, but it should work:

We have $$ \left\lfloor \frac{x}{10^i} \right\rfloor = \sum_{k=0}^n d_k \left\lfloor \frac{10^k}{10^i} \right\rfloor = \sum_{k=i}^n d_k 10^{k-i} $$ where $\lfloor.\rfloor$ means rounding down to the next integer (floor function): $$ \lfloor x \rfloor = \max\, \{ k \in \mathbb{Z} \left| \, k \le x \right. \} $$

So we could use $$ d_i = \left\lfloor \frac{x}{10^i} \right\rfloor \mbox{mod } 10 $$ where $\mbox{mod } 10$ is the remainder of a division by $10$.

If you do not have that basic operation, you could try $$ x \mbox{ mod } 10 = x - 10 \left\lfloor \frac{x}{10} \right\rfloor $$