#include <bits/stdc++.h>
#pragma GCC optimize(2, 3, "Ofast")
#pragma GCC target("avx", "avx2")
using namespace std;
template <typename T1, typename T2>
void ckmin(T1 &a, T2 b) {
  if (a > b) a = b;
}
template <typename T1, typename T2>
void ckmax(T1 &a, T2 b) {
  if (a < b) a = b;
}
int read() {
  int x = 0, f = 0;
  char ch = getchar();
  while (!isdigit(ch)) f |= ch == '-', ch = getchar();
  while (isdigit(ch)) x = 10 * x + ch - '0', ch = getchar();
  return f ? -x : x;
}
template <typename T>
void print(T x) {
  if (x < 0) putchar('-'), x = -x;
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}
template <typename T>
void print(T x, char let) {
  print(x), putchar(let);
}
const int N = 25;
char a[N];
int len, k;
void solve() {
  scanf("%s%d", a + 1, &k);
  len = strlen(a + 1);
  for (int i = 1; i <= len; i++) a[i] ^= '0';
  long long ans = 1e18;
  long long __ = 0;
  if (k == 1) {
    for (int i = 1; i <= len + 1; i++) __ = 10ll * __ + 1;
  } else {
    __ = 1;
    for (int i = 2; i <= len + 1; i++) __ *= 10ll;
  }
  ckmin(ans, __);
  set<int> nums;
  for (int i = 0; i <= len; i++) {
    if (i) nums.insert(a[i]);
    if ((int(nums.size())) > k || i == len) {
      break;
    }
    if (a[i + 1] == 9) continue;
    int t = a[i + 1];
    auto it = nums.lower_bound(t + 1);
    if (it == nums.end()) {
      if ((int(nums.size())) == k) continue;
    }
    set<int> num = nums;
    if ((int(num.size())) < k && !num.count(t + 1)) num.insert(t + 1);
    it = num.lower_bound(t + 1);
    int way = *it;
    long long _ = 0;
    for (int j = 1; j <= i; j++) _ = 10ll * _ + a[j];
    _ = 10ll * _ + way;
    if ((int(num.size())) < k) num.insert(0);
    it = num.begin();
    way = *it;
    for (int j = i + 2; j <= len; j++) _ = 10ll * _ + way;
    ckmin(ans, _);
  }
  if ((int(nums.size())) <= k) {
    long long _ = 0;
    for (int i = 1; i <= len; i++) _ = 10ll * _ + a[i];
    ckmin(ans, _);
  }
  print(ans, '\n');
}
int main() {
  int T = read();
  while (T--) {
    solve();
  }
  return 0;
}
