Run, Run, Runaround Numbers
Time limit1sMemory limit128 MB
For each number R with 2 to 7 digits, find the smallest runaround number (distinct digits 1 to 9, jumps wrap around and visit every position once before returning) that is at least R.
- Level
Medium4 of 10
- Topics
- Simulation, Brute force, Implementation
- Solved
- No attempts yet
Problem
An N-digit runaround number is defined as follows:
- It is an integer with exactly N digits, each between 1 and 9 inclusive.
- The digits form a sequence in which each digit tells where the next digit of the sequence is: read the digit as the number of positions to move to the right to reach the next digit. Counting wraps around from the rightmost digit back to the leftmost when needed.
- The leftmost digit is the first digit of the sequence, and the sequence must return to this digit after every digit of the number has been used exactly once.
- No digit appears more than once in the number.
For example, we verify that 81362 is a runaround number as follows:
- Start at the leftmost digit, 8.
8 1 3 6 2 - - Move 8 positions to the right, landing on 6 (note the wraparound).
8 1 3 6 2 - - - Move 6 positions to the right, landing on 2.
8 1 3 6 2 - - - - Move 2 positions to the right, landing on 1.
8 1 3 6 2 - - - - - Move 1 position to the right, landing on 3.
8 1 3 6 2 - - - - - - Move 3 positions to the right, returning to 8, where we started.
8 1 3 6 2 = - - - -
Input
You are given one or more lines, each containing a single integer R with between 2 and 7 digits. For each R, find the smallest runaround number that is greater than or equal to R; such a number always exists for every input value. The input ends with a line that contains only the digit 0 in the first column; do not process that line.
Output
For each input value, in order, print one line in the form Case k: X, where k is the 1-based index of the query and X is the smallest runaround number greater than or equal to that query's R.