Given a digit string of up to 40 wheels, find the minimum number of single-digit advances (with cascading carries) to reach a palindrome.
Hard8Dynamic programmingGreedyMathImplementationNo attempts yetTime limit1sMemory limit512 MB
"Sabotage!" exclaimed J.R. Diddly, president and founder of Diddly Widgets Inc.
"Vandalism, perhaps. Nothing's actually been damaged." responded Robert Lackey, the chief accountant.
Both were staring up at the large counter suspended above the factory floor, a counter that had faithfully recorded the number of widgets that had come off the assembly line since the factory was opened. Someone had changed the number being displayed.
"It's a palindrome." said Lackey. "It reads the same forwards as backwards."
"What I don't understand," said Diddly, "is why our security guards didn't catch the vandals during their regular sweeps. It must have taken them hours to click forward to this new number, one step at a time."
"No." replied Lackey. "Although we only advance the rightmost digit each time a new widget is built, it's possible to spin any of the digits. With a little planning, this might have taken only a few seconds."
Consider a digital counter consisting of k wheels, each showing a digit from 0 to 9. Each wheel is mounted so that it can advance to the next digit in a single step, for example from 3 to 4, or from 8 to 9.
It is also possible to advance from digit 9 to digit 0. When this happens, the wheel on its immediate left also advances to the next digit automatically. The effect can cascade over several wheels to the left, but all of it happens inside a single step. The leftmost wheel has no wheel to its left, so when it advances from 9 to 0 the carry is simply lost.
Given the current setting of the counter, find the smallest number of steps needed to reach a palindrome. The palindrome must respect leading zeros, so 0011 is not a palindrome.
Take the input 610. Spinning the wheel that shows 6 four times gives 010, so four steps are enough.
The input consists of a single line containing an integer of 1 to 40 digits. The number of digits in the input is the number of wheels on the counter. The number may contain leading zeros.
Print a single line containing one integer, the minimum number of wheel advances required to produce a palindrome.