Find the digit-distinct number (no repeated digit) closest to N, breaking ties toward the smaller value.
Medium6Brute forceGreedyImplementationMathNo attempts yetTime limit1sMemory limit256 MB
Junha, who turns seven soon, likes playing with wooden tiles that have numbers on them. There are 10 tiles in total, and each tile carries one digit from 0 to 9. Junha likes that lining the tiles up makes a larger number, and that the number of combinations is huge. Today he was again staring at 9876543210, the largest number the tiles can make, too excited to sit still. Gangmin, who had watched long enough, started to tease him.
"You cannot even make 333 with those, can you?"
Annoyed, Junha rearranged the tiles in a hurry and answered.
"I cannot make 333, but 329 is close enough!"
Gangmin found the answer ridiculous, so he decided to push further.
"Really? Then what about 44223344?"
Junha's mind went blank. Write a program that does the arithmetic for him so he does not give up on math.
Each digit is printed on exactly one tile, so the numbers Junha can build are the numbers that never repeat a digit. The leading digit is never 0.
The first line contains the number N that Gangmin asked about. (1≤N≤1012)
Print, on the first line, the number whose difference from N is smallest among all numbers built by using each digit from 0 to 9 at most once. The leading digit cannot be 0. If two numbers share the smallest difference, print the smaller one.