The Next Number

Given N, the count of each nonzero digit in N defines the whole list; find the next number that has exactly those digit counts.

Medium7GreedyBacktrackingCombinatoricsImplementationNo attempts yetTime limit5sMemory limit512 MB

Problem

You write out a list of numbers. For each digit ii from 1 to 9, the list holds every positive integer whose decimal representation contains exactly DiD_i copies of the digit ii. The number of zeros is not restricted. You write the numbers in ascending order.

For example, if you write every number with two 1s and one 5, the list starts 115, 151, 511, 1015, 1051.

You are given NN, the last number you wrote. The counts DiD_i are the digit counts of NN itself. Compute the next number in the list.

Input

The first line contains an integer TT, the number of test cases. Each of the next TT lines contains one integer NN.

Limits

  • 1T501 \le T \le 50
  • 1N1061 \le N \le 10^6

Output

For each test case, print one line in the form

Case #X: K

where XX is the test case number starting from 1 and KK is the number that follows NN in the list.