smallest number for given sum of digits I am trying to find the smallest number if we are given the sum of its digits. Suppose that sum of digits  is 9 then it should be 9 instead of 18,36,63 and similarly if sum of digits is  11 then desired answer is 29 not 92 or any other number bigger than 29.I tried to write sum of all numbers upto 53 and got this but i am not able to come up with a general formula.
                        from 1 to 9 it is just 9.FROM 10 to 18 it is 19,29,39,...... and for 19(1+9) it is 199  that is increase by 100.
from 19 to 27 it is 199,299,399,499.... and for 28 it is 1999 that is increase by 1000.
from 29 to 36 it is 29999,39999,49999,..... for 37 it is 19999 (increse by 10000).
for 38 to 45 it is it is 29999,39999,49999,........999999 and for 46 it is 199999 (increased by 100000)
In our so-called positional numeration system, the digits get a weight that increases from right to left, following the powers of ten (units, tens, hundreds, thousands...).

So to minimize the number you will allocate the budget in priority to the positions with the smallest weight.

This is why the solution is by putting as many $9$s to the right as you can, preceded by the remainder of the budget. There will be $b\text{ div }9$ nines and the digit $b\bmod9$, forming the number 

$$(b\bmod 9)10^{b\text{ div }9}+10^{b\text{ div }9}-1=(b\bmod 9+1)10^{b\text{ div }9}-1.$$



If on the opposite you want to maximize the sum, then you must forbid the digit $0$ (because you could insert them "for free"), and the solution is formed by a maximum of $9$s followed by the remainder, i.e.

$$10\,(10^{b\text{ div }9}-1)+b\bmod9$$ unless $b\bmod9=0$, then

$$10^{b\text{ div }9}-1.$$
I have found a general formula to find the smallest number whose digits sum up to S and has M digits. Here is a python implementation of it:

def bla(M,S):
    n=(S+7)//9
    sl=9*n -7
    c=10**(n-1)
    b=10**(M-1)
    p=int((2+S-sl)*c -1)
    return p+b


If you have any doubts please comment below.