Under construction

Still being built. Things may change

Tidy Numbers (Large)

Time limit5sMemory limit512 MB

Summary
Given N up to 10^18, find the largest number not exceeding N whose decimal digits are in non-decreasing order.
Level

Medium5 of 10

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

Problem

Tatiana likes to keep things tidy. Her toys are sorted from smallest to largest, her pencils from shortest to longest, and her computers from oldest to newest. One day, while practicing her counting, she noticed that some integers have their digits in non-decreasing order when written in base 10 with no leading zeroes. Examples are 8, 123, 555, and 224488. She decided to call such an integer a tidy number. Numbers without this property, such as 20, 321, 495, and 999990, are not tidy.

She has just counted every positive integer from 1 to NN in ascending order. What was the last tidy number she counted?

Input

The first line contains the number of test cases TT. Each of the next TT lines describes one test case with a single integer NN, the last number Tatiana counted.

Limits

  • 1≤T≤1001 \le T \le 100
  • 1≤N≤10181 \le N \le 10^{18}

Output

For each test case, print one line of the form Case #x: y, where xx is the test case number starting from 1 and yy is the last tidy number Tatiana counted.

Examples6

  1. Example 1

    Input
    4
    132
    1000
    7
    111111111111111110
    
    Expected output
    Case #1: 129
    Case #2: 999
    Case #3: 7
    Case #4: 99999999999999999
    
  2. Example 2

    Input
    1
    1
    
    Expected output
    Case #1: 1
    
  3. Example 3

    Input
    9
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    Expected output
    Case #1: 1
    Case #2: 2
    Case #3: 3
    Case #4: 4
    Case #5: 5
    Case #6: 6
    Case #7: 7
    Case #8: 8
    Case #9: 9
    
  4. Example 4

    Input
    5
    10
    20
    321
    495
    999990
    
    Expected output
    Case #1: 9
    Case #2: 19
    Case #3: 299
    Case #4: 489
    Case #5: 899999
    
  5. Example 5

    Input
    7
    8
    123
    555
    224488
    123456789
    111111111111111111
    999999999999999999
    
    Expected output
    Case #1: 8
    Case #2: 123
    Case #3: 555
    Case #4: 224488
    Case #5: 123456789
    Case #6: 111111111111111111
    Case #7: 999999999999999999
    
  6. Example 6

    Input
    1
    1000000000000000000
    
    Expected output
    Case #1: 999999999999999999