Is there a math function that takes in a number n and return a number with the digits of n sorted by value?

48 Views Asked by At

The idea crossed my mind of a function that would take in an integer n and return an integer of the digits of n in order.

e.g:
g(184729) = 987421
g(1212121212) = 2222211111
g(1234567890) = 9876543210

I looked it up and saw a similar question, but the answer did not satisfy me as I was looking for one using only basic arithmetic operations, summations, logarithme and modulo.

1

There are 1 best solutions below

6
On

So the answer I came up with might not be the best, but I am satisfied with it.
I splited the following answer in 4 functions (for obvious reasons) but it can be made into one single function.

First, i(x,n) returns the nth digit of x
$i\left(x,n\right)=\left\lfloor\operatorname{mod}\left(\frac{x}{10^{n}},10\right)\right\rfloor$

c(x)+1 returns the length of x
$c\left(x\right)=\left\lfloor\log\left(x\right)\right\rfloor$

f(x,n) counts how many time the digit n is in x
$f\left(x,n\right)=\sum_{p=0}^{c\left(x\right)}0^{\left|i\left(x,p\right)-\operatorname{mod}\left(n,10\right)\right|}$

Finally, g(x) checks f(x) for how many time each digit is in x, multiply them by $\frac{1}{9}$ multiply by 10 one last time so the summation of digits don't overlap
$g\left(x\right)=\left(\sum_{n=1}^{9}\left\lfloor\left(\frac{1}{9}\right)\cdot10^{f\left(x,n\right)}\right\rfloor\cdot n\cdot10^{\sum_{k=1}^{n-1}f\left(x,k\right)}\right)\cdot10^{f\left(x,0\right)}$