<script>
function
trickyCase(s, index)
{
let index1 = -1;
for
(let i = index - 1; i >= 0; i--)
{
let digit = s[i].charCodeAt() -
'0'
.charCodeAt();
if
(digit != 8)
{
index1 = i;
break
;
}
}
if
(index1 == -1)
return
2 * Math.pow(10, s.length);
let num = 0;
for
(let i = 0; i < index1; i++)
num = num * 10 + (s[i].charCodeAt() - '0
'.charCodeAt());
// if non-8 is even or odd
// than add the next even.
if (s[index1].charCodeAt() % 2 == 0)
num = num * 10 +
(s[index1].charCodeAt() - '
0
'.charCodeAt() + 2);
else
num = num * 10 +
(s[index1].charCodeAt() - '
0
'.charCodeAt() + 1);
// add 0 to right of 9
for (let i = index1 + 1;
i < s.length; i++)
num = num * 10;
return num;
}
// function to return the smallest number
// with all digits even
function smallestNumber(n)
{
let num = 0;
let s = "";
let duplicate = n;
// convert the number to
// string to perform operations
while (n > 0)
{
s = String.fromCharCode(n % 10 + 48) + s;
n = parseInt(n / 10, 10);
}
let index = -1;
// find out the first odd number
for (let i = 0; i < s.length; i++)
{
let digit = s[i].charCodeAt() - '
0
'.charCodeAt();
let val = digit & 1;
if (val == 1)
{
index = i;
break;
}
}
// if no odd numbers are there,
// than n is the answer
if (index == -1)
return duplicate;
// if the odd number is 9,
// than tricky case handles it
if (s[index] == '
9
')
{
num = trickyCase(s, index);
return num;
}
// add all digits till first odd
for (let i = 0; i < index; i++)
num = num * 10 +
(s[i].charCodeAt() - '
0
'.charCodeAt());
// increase the odd digit by 1
num = num * 10 +
(s[index].charCodeAt() - '
0'.charCodeAt() + 1);
for
(let i = index + 1;
i < s.length; i++)
num = num * 10;
return
num;
}
let N = 2397;
document.write(smallestNumber(N));
</script>