import java.util.Scanner;
import java.io.FileInputStream;
public class EarningMoney {
public static int N = 0;
public static int[][] arr = new int[11][10000];
public static void main(String args[]) throws Exception {
System.setIn(new FileInputStream("input.txt"));
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int tc = 1; tc <= T; tc++) {
String num = sc.next();
int size = num.length();
N = sc.nextInt();
arr[0][0] = Integer.parseInt(num);
int max = 0;
int count = 0;
int count2 = 1;
for (int i = 0; i < N; i++) {
count = count2;
count2 = 0;
for (int j = 0; j < count; j++) {
String string = String.valueOf(arr[i][j]);
while (string.length() < size) {
string = "0" + string;
}
char[] nums = string.toCharArray();
for (int k = 0; k < string.length() - 1; k++) {
for (int l = k + 1; l < string.length(); l++) {
char t = nums[k];
nums[k] = nums[l];
nums[l] = t;
int value = Integer.parseInt(String.valueOf(nums));
boolean check = false;
for (int m = 0; m < count2; m++) {
if (arr[i + 1][m] == value) {
check = true;
break;
}
}
if (!check) {
arr[i + 1][count2++] = value;
}
if (i == N - 1 && max < value) {
max = value;
}
t = nums[k];
nums[k] = nums[l];
nums[l] = t;
}
}
}
}
System.out.println("Case #" + tc + "\n" + max);
}
}
}