Beware that the solution can exceed the capacity of a 32 bits int (in the worst,case, N=99, the solution is 99999999999).
Your input loop is better written with a while (true) if ... break
rather than if () ... else while () ...
, less readable and with duplication of some code.
You are using a "brute force" approach, by trying all integers in the allowed range and recomputing the sum of digits from scratch. Assuming that the solution is the integer S
having d
digits, you will be performing about (S-M)d
additions.
Anyway, assuming that the sum of the digits of M
is smaller than N
, the solution is quickly achieved by setting the digits to 9, starting from the right, until the sum N
is reached, if I am right. This takes O(N)
additions only, an important saving in most cases. (100 (1) > 109 (10) > 119 (11)
).
Now if the sum of the digits of M
exceeds N
, the solution requires deeper analysis. You will need to modify M
in such a way that its value increases while the sum its digits decreases. I have not tried that, but I wouldn't be surprised that a fast solution remained possible.
Update:
In the second case, you will increase the nonzero digits from the right so that they saturate and generate a carry. (14503 (13) > 14510 (11) > 14600 (11) > 15000 (6) > 60000 (6)
) When the sum falls below M
, you are back in the first case.