#include <bits/stdc++.h>

const int N = 1000;

int best[2][N + 1];
bool dp[N + 1][N + 1];

int main()
{
  for (int o = 0; o < 2; ++ o) {
    memset(dp, 0, sizeof(dp));
    dp[1][o] = true;
    for (int i = 1; i < N; ++ i) {
      for (int j = 0; j <= i; ++ j) {
        if (dp[i][j]) {
          dp[i + 1][j] = true;
          if (j < i) {
            dp[i + 1][j + 2] = true;
          }
          if (j) {
            dp[i + 1][j] = true;
          }
        }
      }
    }
    for (int i = 1; i <= N; ++ i) {
      int &j = best[o][i] = i;
      while (!dp[i][j]) {
        j --;
      }
    }
  }
  std::ios::sync_with_stdio(false);
  int T;
  std::cin >> T;
  while (T --) {
    int n, d;
    std::cin >> n >> d;
    int result = 0;
    for (int i = 0; i < 7; ++ i) {
      result += best[d >> i & 1][n] << i;
    }
    std::cout << result << "\n";
  }
}
