This page is still under construction.

Parts of this page are still being built. What you see may change.

The Next Number (Large)

Time limit5sMemory limit512 MB

Summary
Given N, find the next integer whose count of each nonzero digit matches that of N, with zeros unrestricted.
Level

Medium6 of 10

Topics
Combinatorics, Greedy, Math, Implementation
Solved
No attempts yet

Problem

For each digit ii from 1 to 9, let DiD_i be the number of times ii occurs in the decimal representation of NN. You write out, in ascending order, every positive integer whose decimal representation contains the digit ii exactly DiD_i times for every ii from 1 to 9. The number of times the digit 0 occurs is not restricted. No number has a leading zero.

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

You are given NN, the last number you wrote. 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 a single integer NN.

Limits

  • 1≤T≤5001 \le T \le 500
  • 1≤N≤10201 \le N \le 10^{20}

Output

For each test case, print one line in the following format.

Case #X: K

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

Examples2

  1. Example 1

    Input
    3
    115
    1051
    6233
    
    Expected output
    Case #1: 151
    Case #2: 1105
    Case #3: 6323
    
  2. Example 2

    Input
    2
    511
    1015
    
    Expected output
    Case #1: 1015
    Case #2: 1051