<script>
function
helper(d, s)
{
let ans = [];
for
(let i = 0; i < d; i++)
{
ans.push(
"0"
);
}
for
(let i = d - 1; i >= 0; i--)
{
if
(s >= 9)
{
ans[i] ='9
';
s -= 9;
}
// Put remaining sum
else
{
let c = String.fromCharCode(
s + '
0
'.charCodeAt(0));
ans[i] = c;
s = 0;
}
}
return ans.join("");
}
// Function to find the smallest
// number greater than Y
// whose sum of digits is X
function findMin(x, Y)
{
// Convert number y to String
let y = Y.toString();
let n = y.length;
let p = [];
for(let i = 0; i < n; i++)
{
p.push(0);
}
// Maintain prefix sum of digits
for(let i = 0; i < n; i++)
{
p[i] = y[i].charCodeAt(0) -
'
0
'.charCodeAt(0);
if (i > 0)
{
p[i] = p[i] + p[i - 1];
}
}
// Iterate over Y from the back where
// k is current length of suffix
for(let i = n - 1, k = 0;; i--, k++)
{
// Stores current digit
let d = 0;
if (i >= 0)
{
d = y[i].charCodeAt(0) -
'
0
'.charCodeAt(0);
}
// Increase current digit
for(let j = d + 1; j <= 9; j++)
{
let r = j;
// Sum upto current prefix
if (i > 0)
{
r += p[i - 1];
}
// Return answer if remaining
// sum can be obtained in suffix
if (x - r >= 0 && x - r <= 9 * k)
{
// Find suffix of length k
// having sum of digits x-r
let suf = helper(k, x - r);
let pre = "";
if (i > 0)
pre = y.substring(0, i);
// Append current character
let cur = String.fromCharCode(
j + '
0'.charCodeAt(0));
pre += cur;
return
pre + suf;
}
}
}
}
let x = 18;
let y = 99;
document.write(findMin(x, y));
</script>