Using a function to order an integer's digits from least to greatest?

106 Views Asked by At

Say you have an integer denoted as $n$. Is it possible to make a purely mathematical function that could take $n$ and order its digits from least to greatest?

I know how to do this programatically. I would simply break the integer up into a list composed of its digits, then iterate through that list with a for loop that compares the digits, and so on and so forth.

However, how could I do this without any data structures, manipulating $n$ only mathematically?

EDIT:

When I say manipulating $n$ only mathematically, I mean with arithmetic only. No breaking it up into a list or anything similar.

2

There are 2 best solutions below

4
On BEST ANSWER

$$ f(n) = \min\left\{\sum_{k=0}^{n-1} a_{\sigma(k)} 10^k\colon \sigma\in\Sigma_n,\ \sum_{k=0}^{n-1} a_k 10^k = n,\ a_k\in\{0,1,2,3,4,5,6,7,8,9\}\right\} $$ where $\Sigma_n$ is the set of permutations of $\{0,1,\dots,n-1\}$.

3
On

You're going to need several levels of logarithms and floor functions.

EDIT: Let's say we start with 121.

$log 121 ≈ 2.0828$

$\lfloor{log 121}\rfloor = 2$

$10^{\lfloor{log 121}\rfloor} = 100$

$\frac{121}{10^{\lfloor{log 121}\rfloor}} = 1.21$

$\lfloor \frac{121}{10^{\lfloor{log 121}\rfloor}} \rfloor = 1$ as the first digit

$121-1*10^{\lfloor{log 121}\rfloor} = 21$

$log21 ≈ 1.3222$

...

$\lfloor \frac{21}{10^{\lfloor{log 21}\rfloor}} \rfloor = 2$ as the second digit

$121-1*10^{\lfloor{log 121}\rfloor} - 2*10^{\lfloor{log 121-1*10^{\lfloor{log 121}\rfloor}}\rfloor} = 1$

...

$\lfloor \frac{1}{10^{\lfloor{log 1}\rfloor}} \rfloor = 1$ as the third digit

We now have the digits 1;1; and 2.