Number Theory – Formula for Reversing Digits of a Positive Integer

elementary-number-theory

I was able to work out the cases for $n$ having up to $4$ digits and was wondering if someone could verify my generalization to $m$ digits. Here I am assuming that when a reversal results in there being a leading $0$ it get ignored (e.g. $76130$ gets reversed to $3167$, $998700$ to $7899$ etc.)

I believe the function can be expressed as $r(n): \mathbb{N} \rightarrow \mathbb{N}$
$$r(n) = \left \lfloor \frac{n}{10^m}\right \rfloor +\sum_{k=0}^{m-1}10^{m-k} \left( \left \lfloor\frac{n}{10^k} \right \rfloor-10 \left \lfloor \frac{\left \lfloor \frac{n}{10^k}\right \rfloor}{10}\right \rfloor \right)$$

where again, $n$ has $m$ digits.

It seems like this combination of the floor function and powers of 10 is the only way to achieve this but is this true?

Best Answer

Your first term is always $0$ because $\lfloor \log_{10} n \rfloor = m-1$, and you’re off by a factor of $10$; for example, by your formula

$$\begin{align*} r(123)&=\left\lfloor\frac{123}{1000}\right\rfloor+\sum_{k=0}^210^{3-k}\left(\left\lfloor\frac{123}{10^k}\right\rfloor-10\left\lfloor\frac1{10}\left\lfloor\frac{123}{10^k}\right\rfloor\right\rfloor\right)\\\\ &=0+1000(123-120)+100(12-10)+10(1-0)\\ &=3210 \end{align*}$$

instead of the correct $321$. However,

$$r(n)=\sum_{k=0}^{m-1}10^{m-1-k}\left(\left\lfloor\frac{n}{10^k}\right\rfloor-10\left\lfloor\frac1{10}\left\lfloor\frac{n}{10^k}\right\rfloor\right\rfloor\right)$$

does the trick.

Suppose that $n=\sum_{i=0}^{m-1}d_k10^i$, where each $d_i\in\{0,1,\dots,9\}$, and $d_{m-1}\ne 0$, so that the decimal expansion of $n$ is $d_{m-1}d_{m-2}\ldots d_1d_0$. Then

$$\left\lfloor\frac{n}{10^k}\right\rfloor=\sum_{i=k}^{m-1}d_i10^{i-k}=10\sum_{i=k+1}^{m-1}d_i10^{i-k}+d_k\;,$$

so

$$\left\lfloor\frac{n}{10^k}\right\rfloor-10\left\lfloor\frac1{10}\left\lfloor\frac{n}{10^k}\right\rfloor\right\rfloor=\left(10\sum_{i=k+1}^{m-1}d_i10^{i-k}+d_k\right)-10\sum_{i=k+1}^{m-1}d_i10^{i-k}=d_k\;,$$

and

$$r(n)=\sum_{k=0}^{m-1}10^{m-1-k}d_k=\sum_{k=0}^{m-1}d_{(m-1)-k}10^k\;,$$

whose decimal expansion is $d_0d_1\ldots d_{m-2}d_{m-1}$, as desired.

Related Question