#include <bits/stdc++.h>
using namespace std;
int difdig(int x) {
  int tmp = 0;
  while (x != 0) {
    tmp |= (1 << (x % 10));
    x /= 10;
  }
  return __builtin_popcount(tmp);
}
int main() {
  int _;
  cin >> _;
  while (_--) {
    int n, k;
    cin >> n >> k;
    while (difdig(n) > k) {
      int r = 1;
      int c = n;
      while (difdig(c) > k) {
        c /= 10;
        r *= 10;
      }
      r /= 10;
      n = (n / r + 1) * r;
    }
    cout << n << '\n';
  }
  return 0;
}
