let inputs = []

function read() {
    return inputs.pop();
}

function readInt() {
    return parseInt(read());
}

function solve() {
    let test = readInt();
    while (test--) {
        let n = read();
        let k = readInt();
        let d = n.length;
        function can(s) {
            used = new Array(10).fill(0);
            for (let i = 0; i < s.length; i++) {
                used[parseInt(s[i])] = 1;
            }
            let cnt = 0;
            for (let i = 0; i < 10; i++) {
                cnt += used[i];
            }
            if (k < cnt) {
                return 0;
            }
            let mx = 0;
            for (let i = 0; i < 10; i++) if (used[i]) {
                mx = Math.max(mx, i);
            }
            if (cnt < k) {
                mx = 9;
            }
            while (s.length < n.length) {
                s = s + mx;
            }
            return n <= s;
        }
        s = "";
        while (s.length < n.length) {
            let found = 0;
            for (let i = 0; i < 10; i++) {
                let s2 = s;
                s2 += i;
                if (can(s2)) {
                    s = s2;
                    found = 1;
                    break;
                }
            }
            if (!found) {
                s = "";
                break;
            }
        }
        if (s != "") {
            console.log(s);
        }
        else {
            s = "1";
            for (let i = 0; i < n.length; i++) {
                s += "0";
            }
            console.log(s);
        }
    }
}

function main() {
    inputs = inputString.trim().split(/\n| /).map((string) => string.trim());
    inputs.reverse();
    solve();
}

let inputString = '';

process.stdin.on('data', (inputStdin) => { inputString += inputStdin; });

process.stdin.on('end', (_) => { main(); });

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const revPow2 = {}
for (let e = 0; e < 15; ++e) revPow2[1 << e] = e
function solve(e, n) {
  const t = String(e)
      .split('')
      .map(e => Number(e)),
    r = t.length,
    i = new Array(t.length)
  return (
    (function e(n, s, o) {
      if (o === r) return !0
      const u = t[o],
        d = 1 << u
      if (n & d && ((i[o] = u), e(n, s, o + 1))) return !0
      if (s > 0) {
        if (((i[o] = u), e(n | d, s - 1, o + 1))) return !0
        if (9 === u) return !1
        let t
        ;(i[o] = u + 1),
          (t =
            1 & n || s > 1 || n & (1 << (u + 1))
              ? 0
              : revPow2[(n |= 1 << (u + 1)) & -n])
        for (let e = o + 1; e < r; ++e) i[e] = t
        return !0
      }
      let a = u + 1
      for (; a < 10 && !(n & (1 << a)); ++a);
      if (10 === a) return !1
      i[o] = a
      const l = revPow2[n & -n]
      for (let e = o + 1; e < r; ++e) i[e] = l
      return !0
    })(0, n, 0),
    Number(i.join(''))
  )
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const [n, t] = e.readIntegersOfLine(),
      r = solve(n, t)
    e.print(r + '\n')
  }
})

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      for (let i = 1; i < n.length; i++) {
         if (n[i] === firstC) {
            continue;
         }
         if (n[i] < firstC) {
            write(('' + firstC).repeat(n.length));
            return ('' + firstC).repeat(n.length);
         }
         if (n[i] > firstC) {
            write(('' +(firstC + 1)).repeat(n.length));
            return ('' +(firstC + 1)).repeat(n.length);
         }
      }
      write(('' + firstC).repeat(n.length));
      return ('' + firstC).repeat(n.length);
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return n.join('');
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] < firstC && n[i] < secondC) {
         for (let k = i; k < n.length; k++) {
            n[k] = Math.min(firstC, secondC);
         }
         break;
      }
      if (firstC > n[i] && n[i] > secondC) {
         n[i] = firstC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      if (firstC < n[i] && n[i] < secondC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] > firstC && firstC > secondC) {
         let k = i - 1;
         while(n[k] !== secondC) {
            k--;
         }
         if (k === j) {
            n[j]++;
            for (let k = j + 1; k < n.length; k++) {
               n[k] = firstC === n[j] ? 0 : n[j];
            }
            break;
         }
         n[k++] = firstC;
         for (; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      let k = i - 1;
      while(n[k] !== firstC) {
         k--;
      }
      if (k < j) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[k++] = secondC;
      for (; k < n.length; k++) {
         n[k] = firstC;
      }
      break;
   }
   write(n.join(''));
   return n.join('');
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const ASC0 = '0'.charCodeAt(0);
let k;
let n;
let ans;
function ok(a) {
    const cnt = af(10).fill(0);
    let uniq = 0;
    for (let i = 0; i < a.length; i++) {
        if (cnt[a[i]] == 0) {
            uniq++;
            if (uniq > k) {
                return false;
            }
        }
        cnt[a[i]]++;
    }
    return true;
}
function toI(a) {
    let rv = 0;
    for (let i = 0; i < a.length; i++) {
        rv *= 10;
        rv += a[i];
    }
    return rv;
}
function ge(a, b) {
    check(a.length == b.length);
    for (let i = 0; i < a.length; i++) {
        if (a[i] != b[i]) {
            return a[i] > b[i];
        }
    }
    return true;
}
function solve1() {
    for (let d = 9; d > 0; d--) {
        let t = af(n.length).fill(d);
        if (ge(t, n)) {
            ans = t;
        }
    }
}
function solve2(a, b) {
    for (let i = 0; i < n.length; i++) {
        if (n[i] < b) {
            let t = [...n]; // XXX flash card
            if (t[i] < a) {
                t[i] = a;
            }
            else {
                t[i] = b;
            }
            for (let j = i + 1; j < n.length; j++) {
                t[j] = a;
            }
            if (ge(ans, t)) {
                ans = t;
            }
        }
        if (n[i] != a && n[i] != b) { // end of usable prefix
            return;
        }
    }
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        let s = nextStr();
        k = nextInt();
        n = af(s.length);
        for (let i = 0; i < s.length; i++) {
            n[i] = s.charCodeAt(i) - ASC0;
        }
        if (ok(n)) {
            printf("%d\n", toI(n));
            continue;
        }
        solve1();
        if (k > 1) {
            for (let a = 0; a < 10; a++) {
                for (let b = a + 1; b < 10; b++) {
                    solve2(a, b);
                }
            }
        }
        printf("%j\n", toI(ans));
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

// for (let i = 600000; i <= 633633; i++) {
//     if (solve(i, 2) === '633333') {
//         console.log(i)
//     }
// }

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let min = Math.min(...r)
            let max = Math.max(...r)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (r.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                if (r[i - 1] < max) {
                    const uniq = r.filter(x => x === r[i - 1]).length === 1
                    if (r.indexOf(r[i - 1] + 1) >= 0) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    } else if (uniq) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                    } else {
                        let prev = r.pop() + 1
                        while (r.indexOf(prev) < 0) prev++
                        r.push(prev)
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    }
                } else {
                    // the first not equals max
                    let p = i - 1
                    for (; p >= 0; p--) {
                        if (r[p] !== max) break
                    }
                    // has max
                    let hmax = false
                    for (let x = p; x >= 0; x--) {
                        if (r[x] === max) {
                            hmax = true
                            break
                        }
                    }
                    if (!hmax) {
                        p++
                    }
                    r.length = p + 1
                        const uniq = r.filter(x => x === r[p]).length === 1
                        if (r.indexOf(r[p] + 1) >= 0) {
                            r[p]++
                            min = uniq ? 0 : min
                        } else if (uniq) {
                            r[p]++
                            min = Math.min(...r)
                        } else {
                            let prev = r.pop() + 1
                            while (r.indexOf(prev) < 0) prev++
                            r.push(prev)
                    // console.log(r, hmax, uniq)
                            min = uniq ? 0 : min
                        }
                        for (let x = p + 1; x < s.length; x++) {
                            r[x] = min
                        }
                    // } else {
                    //     const uniq = r.filter(x => x === r[p + 1]).length === 1
                    //     r[p + 1]++
                    //     if (k === 1) {
                    //         min = r[p + 1]
                    //     } else {
                    //         min = uniq ? 0 : Math.min(...r.slice(0, p + 2))
                    //     }
                    //     for (let x = p + 2; x < s.length; x++) {
                    //         r[x] = min
                    //     }
                    // }
                }
            }
            break
        }
    }
    return r.join('')
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write(('' +(firstC + 1)).repeat(n.length));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] < firstC && n[i] < secondC) {
         for (let k = i; k < n.length; k++) {
            n[k] = Math.min(firstC, secondC);
         }
         break;
      }
      if (firstC > n[i] && n[i] > secondC) {
         n[i] = firstC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      if (firstC < n[i] && n[i] < secondC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] > firstC && firstC > secondC) {
         let k = i - 1;
         while(n[k] !== secondC) {
            k--;
         }
         if (k === j) {
            n[j]++;
            for (let k = j + 1; k < n.length; k++) {
               n[k] = firstC === n[j] ? 0 : n[j];
            }
            break;
         }
         n[k++] = firstC;
         for (; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      let k = i - 1;
      while(n[k] !== firstC) {
         k--;
      }
      if (k < j) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[k++] = secondC;
      for (; k < n.length; k++) {
         n[k] = firstC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write(('' +(firstC + 1)).repeat(n.length));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] < firstC && n[i] < secondC) {
         for (let k = i; k < n.length; k++) {
            n[k] = Math.min(firstC, secondC);
         }
         break;
      }
      if (firstC > n[i] && n[i] > secondC) {
         n[i] = firstC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      if (firstC < n[i] && n[i] < secondC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] > firstC && firstC > secondC) {
         let k = i - 1;
         while(n[k] !== secondC) {
            k--;
         }
         if (k === j) {
            n[j]++;
            for (let k = j + 1; k < n.length; k++) {
               n[k] = n[j];
            }
            break;
         }
         n[k++] = firstC;
         for (; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      let k = i - 1;
      while(n[k] !== firstC) {
         k--;
      }
      if (k < j) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[k++] = secondC;
      for (; k < n.length; k++) {
         n[k] = firstC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write(('' +(firstC + 1)).repeat(n.length));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] < firstC && n[i] < secondC) {
         for (let k = i + 1; k < n.length; k++) {
            n[k] = Math.min(firstC, secondC);
         }
         break;
      }
      if (firstC > n[i] && n[i] > secondC) {
         n[i] = firstC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      if (firstC < n[i] && n[i] < secondC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] > firstC && firstC > secondC) {
         let k = i - 1;
         while(n[k] !== secondC) {
            k--;
         }
         if (k === j) {
            n[j]++;
            for (let k = j + 1; k < n.length; k++) {
               n[k] = n[j];
            }
            break;
         }
         n[k++] = firstC;
         for (; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      let k = i - 1;
      while(n[k] !== firstC) {
         k--;
      }
      if (k < j) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[k++] = secondC;
      for (; k < n.length; k++) {
         n[k] = firstC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] < firstC && n[i] < secondC) {
         for (let k = i + 1; k < n.length; k++) {
            n[k] = Math.min(firstC, secondC);
         }
         break;
      }
      if (firstC > n[i] && n[i] > secondC) {
         n[i] = firstC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      if (firstC < n[i] && n[i] < secondC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] > firstC && firstC > secondC) {
         let k = i - 1;
         while(n[k] !== secondC) {
            k--;
         }
         if (k === j) {
            n[j]++;
            for (let k = j + 1; k < n.length; k++) {
               n[k] = n[j];
            }
            break;
         }
         n[k++] = firstC;
         for (; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      let k = i - 1;
      while(n[k] !== firstC) {
         k--;
      }
      if (k < j) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[k++] = secondC;
      for (; k < n.length; k++) {
         n[k] = firstC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] < firstC && n[i] < secondC) {
         for (let k = i + 1; k < n.length; k++) {
            n[k] = Math.min(firstC, secondC);
         }
         break;
      }
      if (firstC > n[i] && n[i] > secondC) {
         n[i] = firstC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      if (firstC < n[i] && n[i] < secondC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] > firstC && firstC > secondC) {
         let k = i - 1;
         while(n[k] !== secondC) {
            k--;
         }
         if (k === j) {
            n[j]++;
            for (let k = j + 1; k < n.length; k++) {
               n[k] = n[j];
            }
            break;
         }
         n[k++] = firstC;
         for (; k < n.length; k++) {
            n[k] = secondC;
         }
         break;
      }
      let k = i - 1;
      while(n[k] !== firstC) {
         k--;
      }
      if (k === 0) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[k++] = secondC;
      for (; k < n.length; k++) {
         n[k] = firstC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] > firstC && n[i] > secondC) {
         if (firstC > secondC) {
            let k = i - 1;
            while (n[k] !== secondC) {
               k--;
            }
            if (k !== j) {
               n[k++] = firstC;
               for (;k < n.length; k++) {
                  n[k] = secondC;
               }
               break;
            }
         }
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = Math.min(n[0], n[j]);
         }
         break;
      }
      if (n[i] < firstC && n[i] < secondC) {
         n[i] = Math.min(firstC, secondC);
         for (let k = i + 1; k < n.length; k++) {
            n[k] = n[i];
         }
         break;
      }
      if (n[i] < secondC && n[i] >= firstC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      if (n[i] === secondC) {
         continue;
      }
      debugger;
      n[i] = firstC;
      for (let k = i + 1; k < n.length; k++) {
         n[k] = secondC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j + 1; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] > firstC && n[i] > secondC) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = Math.min(n[0], n[j]);
         }
         break;
      }
      if (n[i] < firstC && n[i] < secondC) {
         n[i] = Math.min(firstC, secondC);
         for (let k = i + 1; k < n.length; k++) {
            n[k] = Math.min(n[0], n[j]);
         }
         break;
      }
      if (n[i] < secondC && n[i] > firstC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[i] = firstC;
      for (let k = i + 1; k < n.length; k++) {
         n[k] = secondC;
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] > firstC && n[i] > secondC) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = Math.min(n[0], n[j]);
         }
         break;
      }
      if (n[i] < firstC && n[i] < secondC) {
         n[i] = Math.min(firstC, secondC);
         for (let k = i + 1; k < n.length; k++) {
            n[k] = Math.min(n[0], n[j]);
         }
         break;
      }
      if (n[i] < secondC && n[i] > firstC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[j]++;
      for (let k = j + 1; k < n.length; k++) {
         n[k] = Math.min(n[0], n[j]);
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   for (let i = j; i < n.length; i++) {
      if (n[i] === firstC || n[i] === secondC) {
         continue;
      }
      if (n[i] > firstC && n[i] > secondC) {
         n[j]++;
         for (let k = j + 1; k < n.length; k++) {
            n[k] = Math.min(n[0], n[j]);
         }
         break;
      }
      if (n[i] < firstC && n[i] < secondC) {
         n[i] = Math.min(firstC, secondC);
         continue;
      }
      if (n[i] < secondC && n[i] > firstC) {
         n[i] = secondC;
         for (let k = i + 1; k < n.length; k++) {
            n[k] = firstC;
         }
         break;
      }
      n[j]++;
      for (let k = j + 1; k < n.length; k++) {
         n[k] = Math.min(n[0], n[j]);
      }
      break;
   }
   write(n.join(''));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function solve() {
   const arr = read().split(' ');
   const n = arr[0].split('').map((x) => Number(x));
   const k = arr[1];
   if (k === '1') {
      const firstC = n[0];
      let isMoreFirst = false;
      for (let i = 1; i < n.length; i++) {
         if (n[i] > firstC) {
            isMoreFirst = true;
         }
      }
      if (isMoreFirst) {
         write((firstC + 1) + '0'.repeat(n.length - 1));
         return;
      }
      write(('' + firstC).repeat(n.length));
      return;
   }
   const firstC = n[0];
   let j = 1;
   while(j < n.length && n[j] === firstC) {
      j++;
   }
   if (j === n.length) {
      write(n.join(''));
      return;
   }
   const secondC = n[j];
   let isMoreSecond = false;
   for (let i = j; i < n.length; i++) {
      if (n[i] > secondC) {
         isMoreSecond = true;
      }
   }
   if (isMoreSecond) {
      write(('' + firstC).repeat(j) + (secondC + 1) + ('' + Math.min(firstC, secondC + 1)).repeat(n.length - j - 1));
      return;
   }
   write(('' + firstC).repeat(j) + secondC + ('' + Math.min(secondC, firstC)).repeat(n.length - j - 1));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let min = Math.min(...r)
            let max = Math.max(...r)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (r.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                if (r[i - 1] < max) {
                    const uniq = r.filter(x => x === r[i - 1]).length === 1
                    if (r.indexOf(r[i - 1] + 1) >= 0) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    } else if (uniq) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                    } else {
                        let prev = r.pop() + 1
                        while (r.indexOf(prev) < 0) prev++
                        r.push(prev)
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    }
                } else {
                    // the first not equals max
                    let p = i - 1
                    for (; p >= 0; p--) {
                        if (r[p] !== max) break
                    }
                    // has max
                    let hmax = false
                    for (let x = p; x >= 0; x--) {
                        if (r[x] === max) {
                            hmax = true
                            break
                        }
                    }
                    if (!hmax) {
                        p++
                    }
                        const uniq = r.slice(0, p + 1)
                            .filter(x => x === r[p]).length === 1
                        if (r.indexOf(r[p] + 1) >= 0) {
                            r[p]++
                            min = uniq ? 0 : min
                        } else if (uniq) {
                            r[p]++
                            min = Math.min(...r.slice(0, p + 1))
                        } else {
                            while (r.indexOf(r[p]) < 0) r[p]++
                            min = uniq ? 0 : min
                        }
                        for (let x = p + 1; x < s.length; x++) {
                            r[x] = min
                        }
                    // } else {
                    //     const uniq = r.filter(x => x === r[p + 1]).length === 1
                    //     r[p + 1]++
                    //     if (k === 1) {
                    //         min = r[p + 1]
                    //     } else {
                    //         min = uniq ? 0 : Math.min(...r.slice(0, p + 2))
                    //     }
                    //     for (let x = p + 2; x < s.length; x++) {
                    //         r[x] = min
                    //     }
                    // }
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let min = Math.min(...r)
            let max = Math.max(...r)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (r.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                if (r[i - 1] < max) {
                    const uniq = r.filter(x => x === r[i - 1]).length === 1
                    if (r.indexOf(r[i - 1] + 1) >= 0) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    } else if (uniq) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                    } else {
                        let prev = r.pop() + 1
                        while (r.indexOf(prev) < 0) prev++
                        r.push(prev)
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    }
                } else {
                    // the first not equals max
                    let p = i - 1
                    for (; p >= 0; p--) {
                        if (r[p] !== max) break
                    }
                    // has max
                    let hmax = false
                    for (let x = p; x >= 0; x--) {
                        if (r[x] === max) {
                            hmax = true
                            break
                        }
                    }
                    if (hmax) {
                        const uniq = r.filter(x => x === r[p]).length === 1
                        if (r.indexOf(r[p] + 1) >= 0) {
                            r[p]++
                            min = uniq ? 0 : min
                        } else if (uniq) {
                            r[p]++
                            min = Math.min(...r)
                        } else {
                            while (r.indexOf(r[p]) < 0) r[p]++
                            min = uniq ? 0 : min
                        }
                        for (let x = p + 1; x < s.length; x++) {
                            r[x] = min
                        }
                    } else {
                        const uniq = r.filter(x => x === r[p + 1]).length === 1
                        r[p + 1]++
                        if (k === 1) {
                            min = r[p + 1]
                        } else {
                            min = uniq ? 0 : Math.min(...r.slice(0, p + 2))
                        }
                        for (let x = p + 2; x < s.length; x++) {
                            r[x] = min
                        }
                    }
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let min = Math.min(...r)
            let max = Math.max(...r)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (r.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                if (r[i - 1] < max) {
                    const uniq = r.filter(x => x === r[i - 1]).length === 1
                    if (r.indexOf(r[i - 1] + 1) >= 0) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    } else if (uniq) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                    } else {
                        let prev = r.pop() + 1
                        while (r.indexOf(prev) < 0) prev++
                        r.push(prev)
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    }
                } else {
                    // the first not equals max
                    let p = i - 1
                    for (; p >= 0; p--) {
                        if (r[p] !== max) break
                    }
                    // has max
                    let hmax = false
                    for (let x = p; x >= 0; x--) {
                        if (r[x] === max) {
                            hmax = true
                            break
                        }
                    }
                    if (hmax) {
                        const uniq = r.filter(x => x === r[p]).length === 1
                        if (r.indexOf(r[p] + 1) >= 0) {
                            r[p]++
                            min = uniq ? 0 : min
                        } else if (uniq) {
                            r[p]++
                            min = Math.min(...r)
                        } else {
                            while (r.indexOf(r[p]) < 0) r[p]++
                            min = uniq ? 0 : min
                        }
                        for (let x = p + 1; x < s.length; x++) {
                            r[x] = min
                        }
                    } else {
                        const uniq = r.filter(x => x === r[p + 1]).length === 1
                        r[p + 1]++
                        min = uniq ? 0 : Math.min(...r.slice(0, p + 2))
                        for (let x = p + 2; x < s.length; x++) {
                            r[x] = min
                        }
                    }
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let min = Math.min(...r)
            let max = Math.max(...r)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (r.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                if (r[i - 1] < max) {
                    const uniq = r.filter(x => x === r[i - 1]).length === 1
                    if (r.indexOf(r[i - 1] + 1) >= 0) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    } else if (uniq) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                    } else {
                        let prev = r.pop() + 1
                        while (r.indexOf(prev) < 0) prev++
                        r.push(prev)
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    }
                } else {
                    // the first not equals max
                    let p = i - 1
                    for (; p >= 0; p--) {
                        if (r[p] !== max) break
                    }
                    // has max
                    let hmax = false
                    for (let x = p; x >= 0; x--) {
                        if (r[x] === max) {
                            hmax = true
                            break
                        }
                    }
                    if (hmax) {
                        const uniq = r.filter(x => x === r[p]).length === 1
                        if (r.indexOf(r[p] + 1) >= 0) {
                            r[p]++
                            r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                        } else if (uniq) {
                            r[p]++
                            r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                        } else {
                            while (r.indexOf(r[p]) < 0) r[p]++
                            r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                        }
                    } else {
                        r[p + 1]++
                        min = Math.min(...r.slice(0, p + 2))
                        for (let x = p + 2; x < s.length; x++) {
                            r[x] = min
                        }
                    }
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let ds = first.map(x => x[0])
            const min = Math.min(...ds)
            const max = Math.max(...ds)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (ds.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else if (ds.indexOf(r[i - 1] + 1) >= 0) {
                r[i - 1]++

                const [a, j] = first.pop()
                r.push(...Array(s.length - r.length).fill(j === i - 1 ? 0 : min))
            } else {
                // the first not equals max
                let p = i - 1
                for (; p >= 0; p--) {
                    if (r[p] !== max) break
                }
                // has max
                let hmax = false
                for (let x = p; x >= 0; x--) {
                    if (r[x] === max) {
                        hmax = true
                        break
                    }
                }
                if (hmax) {
                    const [a, j] = first[first.length - 1]
                    if (j === i - 1) {
                        first.pop()
                        ds = first.map(x => x[0])
                        // the last
                        r[i - 1] = a + 1
                        c = Math.min(a + 1, ...ds)
                        r.push(...Array(s.length - r.length).fill(c))
                    } else {
                        // console.log(r, p, ds, r[p])
                        r[p]++
                        while (ds.indexOf(r[p]) < 0) r[p]++
                        r.push(...Array(s.length - r.length).fill(min))
                    }
                    break
                }
                // x with the max first
                const [a, j] = first.pop()
                ds = first.map(x => x[0])
                r[j] = a + 1
                // first.push([a + 1, j])
                c = first.length ? Math.min(...ds) : a + 1
                for (let x = j + 1; x < s.length; x++) {
                    r[x] = c
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            const ds = first.map(x => x[0])
            const min = Math.min(...ds)
            const max = Math.max(...ds)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (ds.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else if (ds.indexOf(r[i - 1] + 1) >= 0) {
                r[i - 1]++

                const [a, j] = first.pop()
                r.push(...Array(s.length - r.length).fill(j === i - 1 ? 0 : min))
            } else {
                // x with the max first
                const [a, j] = first.pop()
                r[j] = a + 1
                first.push([a + 1, j])
                c = first.length ? Math.min(...first.map(x => x[0])) : a + 1
                for (let x = j + 1; x < s.length; x++) {
                    r[x] = c
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            const ds = first.map(x => x[0])
            const min = Math.min(...ds)
            const max = Math.max(...ds)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (ds.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else if (ds.indexOf(r[i - 1] + 1) >= 0) {
                r[i - 1]++
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                // x with the max first
                const [a, j] = first.pop()
                r[j] = a + 1
                first.push([a + 1, j])
                c = first.length ? Math.min(...first.map(x => x[0])) : a + 1
                for (let x = j + 1; x < s.length; x++) {
                    r[x] = c
                }
            }
            break
        }
    }
    return r.join('')
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    if (k === 1) {
        let a = Array(s.length).fill(s[0]).join('')
        a = +a
        if (a >= n) {
            return a
        } else {
            a = Array(s.length).fill(+s[0] + 1).join('')
            return +a
        }
    } else {
        let a = s[0]
        let b = -1
        for (let i = 1; i < s.length; i++) {
            if (s[i] !== a) {
                b = s[i]
                break
            }
        }
        if (b < 0) return n

        const r = []
        for (let i = 0; i < s.length; i++) {
            if (s[i] !== a && s[i] !== b) {
                a = +a
                b = +b
                let min = Math.min(a, b)
                let max = Math.max(a, b)
                let c = +s[i]
                if (c <= min) {
                    c = min
                    r.push(...Array(s.length - r.length).fill(c))
                } else if (c <= max) {
                    r.push(max)
                    c = min
                    r.push(...Array(s.length - r.length).fill(c))
                } else {
                    let j = i - 1
                    for (; j >= 0; j--) {
                        // the last a
                        if (+s[j] < max) {
                            break
                        }
                    }
                    let hasb = false
                    for (let x = j; x >= 0; x--) {
                        if (+s[x] == b) hasb = true
                    }
                // console.log('hasb', hasb, c, r, j)
                    if (hasb) {
                        r[j] = max
                        c = min
                        r.push(...Array(s.length - r.length).fill(c))
                    } else {
                        let firstb = false
                        for (let x = 0; x < i; x++) {
                            // the first b -> c
                            if (!firstb && r[x] != a) {
                                firstb = true
                                r[x] = max + 1
                        // console.log('firstb')
                            } else {
                                r[x] = a
                            }
                        }
                        c = a
                        r.push(...Array(s.length - r.length).fill(c))
                    }
                }
                break
            } else {
                r.push(s[i])
            }
        }
        return r.join('')
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k))
    }
// })()
})

function solve(n, k) {
    const s = String(n)
    if (k === 1) {
        let a = Array(s.length).fill(s[0]).join('')
        a = +a
        if (a >= n) {
            return a
        } else {
            a = Array(s.length).fill(+s[0] + 1).join('')
            return +a
        }
    } else {
        let a = s[0]
        let b = -1
        for (let i = 1; i < s.length; i++) {
            if (s[i] !== a) {
                b = s[i]
                break
            }
        }
        if (b < 0) return n

        const r = []
        for (let i = 0; i < s.length; i++) {
            if (s[i] !== a && s[i] !== b) {
                a = +a
                b = +b
                let min = Math.min(a, b)
                let max = Math.max(a, b)
                let c = +s[i]
                if (c <= min) {
                    c = min
                    r.push(...Array(s.length - r.length).fill(c))
                } else if (c <= max) {
                    r.push(max)
                    c = min
                    r.push(...Array(s.length - r.length).fill(c))
                } else {
                    let j = i - 1
                    for (; j >= 0; j--) {
                        // the last a
                        if (+s[j] < max) {
                            break
                        }
                    }
                    let hasb = false
                    for (let x = j; x >= 0; x--) {
                        if (+s[x] == b) hasb = true
                    }
                // console.log('hasb', hasb, c, r, j)
                    if (hasb) {
                        r[j] = max
                        c = min
                        r.push(...Array(s.length - r.length).fill(c))
                    } else {
                        let firstb = false
                        for (let x = 0; x < i; x++) {
                            // the first b -> c
                            if (!firstb && r[x] != a) {
                                firstb = true
                                r[x] = c
                        // console.log('firstb')
                            } else {
                                r[x] = a
                            }
                        }
                        c = a
                        r.push(...Array(s.length - r.length).fill(c))
                    }
                }
                break
            } else {
                r.push(s[i])
            }
        }
        return r.join('')
    }
}

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const revPow2 = {}
for (let e = 0; e < 15; ++e) revPow2[1 << e] = e
function solve(e, n) {
  const t = String(e)
      .split('')
      .map(e => Number(e)),
    r = t.length,
    i = new Array(t.length)
  return (
    (function e(n, s, o) {
      if (o === r) return !0
      const u = t[o],
        d = 1 << u
      if (n & d && ((i[o] = u), e(n, s, o + 1))) return !0
      if (s > 0) {
        if (((i[o] = u), e(n | d, s - 1, o + 1))) return !0
        if (9 === u) return !1
        i[o] = u + 1
        const t = 1 & (n |= 1 << (u + 1)) || s > 1 ? 0 : revPow2[n & -n]
        for (let e = o + 1; e < r; ++e) i[e] = t
        return !0
      }
      if (0 === n || 9 === u) return !1
      if (n < 1 << u) return !1
      let a = u + 1
      for (; a < 10 && !(n & (1 << a)); ++a);
      i[o] = a
      const c = revPow2[n & -n]
      for (let e = o + 1; e < r; ++e) i[e] = c
      return !0
    })(0, n, 0),
    Number(i.join(''))
  )
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const [n, t] = e.readIntegersOfLine(),
      r = solve(n, t)
    e.print(r + '\n')
  }
})

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const revPow2 = {}
for (let e = 0; e < 15; ++e) revPow2[1 << e] = e
function solve(e, n) {
  const t = String(e)
      .split('')
      .map(e => Number(e)),
    r = t.length,
    i = new Array(t.length)
  return (
    (function e(n, s, o) {
      if (o === r) return !0
      const u = t[o],
        d = 1 << u
      if (n & d) return (i[o] = u), e(n, s, o + 1)
      if (s > 0) {
        if (((i[o] = u), e(n | d, s - 1, o + 1))) return !0
        if (9 === u) return !1
        i[o] = u + 1
        const t = 1 & (n |= 1 << (u + 1)) || s > 1 ? 0 : revPow2[n & -n]
        for (let e = o + 1; e < r; ++e) i[e] = t
        return !0
      }
      if (0 === n || 9 === u) return !1
      if (n < 1 << u) return !1
      let a = u + 1
      for (; a < 10 && !(n & (1 << a)); ++a);
      i[o] = a
      const c = revPow2[n & -n]
      for (let e = o + 1; e < r; ++e) i[e] = c
      return !0
    })(0, n, 0),
    Number(i.join(''))
  )
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const [n, t] = e.readIntegersOfLine(),
      r = solve(n, t)
    e.print(r + '\n')
  }
})

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const revPow2 = {}
for (let e = 0; e < 15; ++e) revPow2[1 << e] = e
function solve(e, n) {
  const t = String(e)
      .split('')
      .map(e => Number(e)),
    r = t.length,
    i = new Array(t.length)
  return (
    (function e(n, s, o) {
      if (o === r) return !0
      const u = t[o],
        d = 1 << u
      if (n & d) return (i[o] = u), e(n, s, o + 1)
      if (s > 0) {
        if (((i[o] = u), e(n | d, s - 1, o + 1))) return !0
        if (9 === u) return !1
        i[o] = u + 1
        const t = 1 & (n |= 1 << (u + 1)) || s > 1 ? 0 : revPow2[n & -n]
        for (let e = o + 1; e < r; ++e) i[e] = t
        return !0
      }
      if (0 === n) return !1
      if (n < 1 << u) return !1
      let a = u + 1
      for (; a < 10 && !(n & (1 << a)); ++a);
      i[o] = a
      const c = revPow2[n & -n]
      for (let e = o + 1; e < r; ++e) i[e] = c
      return !0
    })(0, n, 0),
    Number(i.join(''))
  )
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const [n, t] = e.readIntegersOfLine(),
      r = solve(n, t)
    e.print(r + '\n')
  }
})

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const revPow2 = {}
for (let e = 0; e < 15; ++e) revPow2[1 << e] = e
function solve(e, n) {
  const t = String(e)
      .split('')
      .map(e => Number(e)),
    r = t.length,
    i = new Array(t.length)
  return (
    (function e(n, s, o) {
      if (o === r) return !0
      const u = t[o],
        d = 1 << u
      if (n & d) return (i[o] = u), e(n, s, o + 1)
      if (s > 0) {
        if (((i[o] = u), e(n | d, s - 1, o + 1))) return !0
        if (9 === u) return !1
        i[o] = u + 1
        const t = 1 & (n |= 1 << (u + 1)) || s > 1 ? 0 : revPow2[n & -n]
        for (let e = o + 1; e < r; ++e) i[e] = t
        return !0
      }
      if (0 === n) return !1
      let a = u + 1
      for (; a < 10 && !(n & (1 << a)); ++a);
      if (10 === a) return !1
      i[o] = u + 1
      const c = revPow2[n & -n]
      for (let e = o + 1; e < r; ++e) i[e] = c
      return !0
    })(0, n, 0),
    Number(i.join(''))
  )
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const [n, t] = e.readIntegersOfLine(),
      r = solve(n, t)
    e.print(r + '\n')
  }
})