You are given two integers $n$ and $m$. Find the $\operatorname{MEX}$ of the sequence $n \oplus 0, n \oplus 1, \ldots, n \oplus m$. Here, $\oplus$ is the bitwise XOR operator .

$\operatorname{MEX}$ of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For example, $\operatorname{MEX}(0, 1, 2, 4) = 3$, and $\operatorname{MEX}(1, 2021) = 0$.


-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 30000$)  — the number of test cases.

The first and only line of each test case contains two integers $n$ and $m$ ($0 \le n, m \le 10^9$).


-----Output-----

For each test case, print a single integer  — the answer to the problem.


-----Examples-----

Input
5
3 5
4 6
3 2
69 696
123456 654321
Output
4
3
0
640
530866


-----Note-----

In the first test case, the sequence is $3 \oplus 0, 3 \oplus 1, 3 \oplus 2, 3 \oplus 3, 3 \oplus 4, 3 \oplus 5$, or $3, 2, 1, 0, 7, 6$. The smallest non-negative integer which isn't present in the sequence i. e. the $\operatorname{MEX}$ of the sequence is $4$.

In the second test case, the sequence is $4 \oplus 0, 4 \oplus 1, 4 \oplus 2, 4 \oplus 3, 4 \oplus 4, 4 \oplus 5, 4 \oplus 6$, or $4, 5, 6, 7, 0, 1, 2$. The smallest non-negative integer which isn't present in the sequence i. e. the $\operatorname{MEX}$ of the sequence is $3$.

In the third test case, the sequence is $3 \oplus 0, 3 \oplus 1, 3 \oplus 2$, or $3, 2, 1$. The smallest non-negative integer which isn't present in the sequence i. e. the $\operatorname{MEX}$ of the sequence is $0$.

Difficulty: MEDIUM_HARD
Tags: Bit manipulation

Sorting

Implementation

Greedy algorithms
Skill types: Bit manipulation

Sorting

Greedy algorithms

Starter code:

Solutions:
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for i in range(30, -1, -1):
		if not 1 << i & n and 1 << i & m:
			ans += 1 << i
		elif 1 << i & n and (not 1 << i & m):
			break
	print(ans)


import sys
LI = lambda : list(map(int, sys.stdin.readline().split()))
MI = lambda : map(int, sys.stdin.readline().split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline())
for _ in range(II()):
	(n, m) = MI()
	(n, p) = (bin(n)[2:], bin(m + 1)[2:])
	l = max(len(n), len(p))
	(n, p) = ('0' * (l - len(n)) + n, '0' * (l - len(p)) + p)
	s = ''
	for i in range(l):
		if n[i] == '1':
			if p[i] == '1':
				s += '0'
			else:
				s += (l - len(s)) * '0'
				break
		elif p[i] == '1':
			s += '1'
		else:
			s += '0'
	print(int(s, 2))


T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	if m < n:
		print(0)
		continue
	N = bin(n)[2:]
	P = bin(m + 1)[2:]
	k = ['0'] * max(len(N), len(P))
	N = '0' * (len(P) - len(N)) + N
	for i in range(len(P)):
		if N[i] == '1' and P[i] == '0':
			break
		if P[i] == N[i]:
			k[i] = '0'
		else:
			k[i] = '1'
	print(int(''.join(k), 2))


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	x = bin(n)[2:].zfill(32)
	y = bin(m)[2:].zfill(32)
	ans = []
	mini = ['1'] * 32
	for i in range(32):
		if y[i] == '1':
			if x[i] == '1':
				ans.append('0')
			else:
				ans.append('1')
		elif x[i] == '1':
			mini = min(mini, ans + ['0'] * (32 - len(ans)))
			ans.append('1')
		else:
			mini = min(mini, ans + ['1'] + ['0'] * (31 - len(ans)))
			ans.append('0')
	print(int(''.join(mini), 2))


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	answer = 0
	if n > m:
		print(0)
	else:
		nbin = bin(n)[2:]
		mbin = bin(m)[2:]
		nlen = len(nbin)
		mlen = len(mbin)
		nbin = '0' * (mlen - nlen) + nbin
		data = ['0'] * mlen
		flg = False
		for i in range(mlen):
			if nbin[i] == '0' and mbin[i] == '1':
				data[i] = '1'
			elif nbin[i] == '1' and mbin[i] == '0':
				data[i] = '0'
				flg = True
				break
		if not flg:
			flg2 = -1
			for i in range(mlen - 1, -1, -1):
				if nbin[i] == '0' and mbin[i] == '0':
					data[i] = '1'
					flg2 = i
					break
			if flg2 >= 0:
				for i in range(flg2 + 1, mlen):
					data[i] = '0'
			else:
				data = ['1'] + ['0'] * mlen
			answer = int(''.join(data), 2)
			print(answer)
		else:
			answer = int(''.join(data), 2)
			print(answer)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for k in range(30, -1, -1):
		if n >= m:
			break
		if n >> k & 1 == m >> k & 1:
			continue
		if m >> k & 1:
			ans |= 1 << k
			n |= 1 << k
	print(ans)


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
for _ in range(ii()):
	(n, m) = il()
	m += 1
	ans = 0
	for i in range(30, -1, -1):
		if n >= m:
			break
		if n & 1 << i == m & 1 << i:
			continue
		if m & 1 << i:
			ans |= 1 << i
			n |= 1 << i
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	if n > m:
		ans = 0
	else:
		l = max(len(bin(n)), len(bin(m))) - 1
		n0 = list('0' * (l - len(bin(n)) + 2) + bin(n)[2:])
		m0 = list('0' * (l - len(bin(m)) + 2) + bin(m)[2:])
		x = [0] * l
		f = 0
		for i in range(l):
			if n0[i] == '0' and m0[i] == '1':
				x[i] = 1
			elif n0[i] == '1' and m0[i] == '0':
				f = 1
				break
		ans = 0
		p = 1
		if not f:
			for i in range(l - 1, -1, -1):
				if n0[i] == m0[i] == '0':
					x[i] = 1
					break
				x[i] = 0
		for i in range(l - 1, -1, -1):
			ans += x[i] * p
			p *= 2
	print(ans)


t = int(input())
for hh in range(0, t):
	(n, m) = [int(x) for x in input().split()]
	if n == 0:
		print(m + 1)
	elif m < n:
		print(0)
	else:
		li = [0] * 34
		idx = 33
		norig = n
		while n > 0:
			if n % 2 == 1:
				li[idx] = 1
			n = n // 2
			idx -= 1
		li1 = []
		po = 1
		for i in range(33, -1, -1):
			if li[i] == 0:
				li1.append(po)
			po = po * 2
		n = m + 1 - norig
		ans = 0
		while n > 0:
			su = 0
			for i in range(0, len(li1)):
				su += li1[i]
				if su >= n:
					n = n - li1[i]
					ans += li1[i]
					break
		print(ans)


import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

def li():
	return list(map(int, sys.stdin.readline().split()))

def mp():
	return map(int, sys.stdin.readline().split())

def inp():
	return int(sys.stdin.readline())

def pr(n):
	return sys.stdout.write(str(n) + '\n')

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	(n, m) = mp()
	ans = 0
	m += 1
	for i in range(30, -1, -1):
		if n >= m:
			break
		if 1 << i & n == 1 << i & m:
			continue
		if 1 << i & m:
			ans |= 1 << i
			n |= 1 << i
	pr(ans)
for _ in range(inp()):
	solve()


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
import random

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	cnt = []
	while n % 2 == 0:
		cnt.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt.append(i)
			n = n / i
	if n > 2:
		cnt.append(int(n))
	return cnt

def primeFactorsCount(n):
	cnt = 0
	while n % 2 == 0:
		cnt += 1
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt += 1
			n = n // i
	if n > 2:
		cnt += 1
	return cnt

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	i = 2
	while i * i <= n:
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
		i += 1
	pr = []
	for i in range(0, n + 1):
		if primes[i]:
			pr.append(i)
	return pr

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def sod(n):
	s = 0
	while n > 0:
		s += n % 10
		n //= 10
	return s
for xyz in range(0, int(input())):
	(n, m) = map(int, input().split())
	if n > m:
		print(0)
	else:
		s1 = binary(n)
		s2 = binary(m + 1)
		l1 = len(s1)
		l2 = len(s2)
		s1 = '0' * (l2 - l1) + s1
		ans = ''
		for i in range(0, l2):
			if s1[i] == s2[i]:
				ans += '0'
			elif s2[i] == '1' and s1[i] == '0':
				ans += '1'
			elif s2[i] == '0' and s1[i] == '1':
				ans += '0' * (l2 - i)
				break
		print(decimal(ans))


def divisors(M):
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	return d

def popcount(x):
	x = x - (x >> 1 & 1431655765)
	x = (x & 858993459) + (x >> 2 & 858993459)
	x = x + (x >> 4) & 252645135
	x = x + (x >> 8)
	x = x + (x >> 16)
	return x & 127

def eratosthenes(n):
	res = [0 for i in range(n + 1)]
	prime = set([])
	for i in range(2, n + 1):
		if not res[i]:
			prime.add(i)
			for j in range(1, n // i + 1):
				res[i * j] = 1
	return prime

def factorization(n):
	res = []
	for p in prime:
		if n % p == 0:
			while n % p == 0:
				n //= p
			res.append(p)
	if n != 1:
		res.append(n)
	return res

def euler_phi(n):
	res = n
	for x in range(2, n + 1):
		if x ** 2 > n:
			break
		if n % x == 0:
			res = res // x * (x - 1)
			while n % x == 0:
				n //= x
	if n != 1:
		res = res // n * (n - 1)
	return res

def ind(b, n):
	res = 0
	while n % b == 0:
		res += 1
		n //= b
	return res

def isPrimeMR(n):
	d = n - 1
	d = d // (d & -d)
	L = [2, 3, 5, 7, 11, 13, 17]
	for a in L:
		t = d
		y = pow(a, t, n)
		if y == 1:
			continue
		while y != n - 1:
			y = y * y % n
			if y == 1 or t == n - 1:
				return 0
			t <<= 1
	return 1

def findFactorRho(n):
	from math import gcd
	m = 1 << n.bit_length() // 8
	for c in range(1, 99):
		f = lambda x: (x * x + c) % n
		(y, r, q, g) = (2, 1, 1, 1)
		while g == 1:
			x = y
			for i in range(r):
				y = f(y)
			k = 0
			while k < r and g == 1:
				ys = y
				for i in range(min(m, r - k)):
					y = f(y)
					q = q * abs(x - y) % n
				g = gcd(q, n)
				k += m
			r <<= 1
		if g == n:
			g = 1
			while g == 1:
				ys = f(ys)
				g = gcd(abs(x - ys), n)
		if g < n:
			if isPrimeMR(g):
				return g
			elif isPrimeMR(n // g):
				return n // g
			return findFactorRho(g)

def primeFactor(n):
	i = 2
	ret = {}
	rhoFlg = 0
	while i * i <= n:
		k = 0
		while n % i == 0:
			n //= i
			k += 1
		if k:
			ret[i] = k
		i += 1 + i % 2
		if i == 101 and n >= 2 ** 20:
			while n > 1:
				if isPrimeMR(n):
					(ret[n], n) = (1, 1)
				else:
					rhoFlg = 1
					j = findFactorRho(n)
					k = 0
					while n % j == 0:
						n //= j
						k += 1
					ret[j] = k
	if n > 1:
		ret[n] = 1
	if rhoFlg:
		ret = {x: ret[x] for x in sorted(ret)}
	return ret

def divisors(n):
	res = [1]
	prime = primeFactor(n)
	for p in prime:
		newres = []
		for d in res:
			for j in range(prime[p] + 1):
				newres.append(d * p ** j)
		res = newres
	res.sort()
	return res

def xorfactorial(num):
	if num == 0:
		return 0
	elif num == 1:
		return 1
	elif num == 2:
		return 3
	elif num == 3:
		return 0
	else:
		x = baseorder(num)
		return 2 ** x * ((num - 2 ** x + 1) % 2) + function(num - 2 ** x)

def xorconv(n, X, Y):
	if n == 0:
		res = [X[0] * Y[0] % mod]
		return res
	x = [X[i] + X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	y = [Y[i] + Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	z = [X[i] - X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	w = [Y[i] - Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	res1 = xorconv(n - 1, x, y)
	res2 = xorconv(n - 1, z, w)
	former = [(res1[i] + res2[i]) * inv for i in range(2 ** (n - 1))]
	latter = [(res1[i] - res2[i]) * inv for i in range(2 ** (n - 1))]
	former = list(map(lambda x: x % mod, former))
	latter = list(map(lambda x: x % mod, latter))
	return former + latter

def merge_sort(A, B):
	(pos_A, pos_B) = (0, 0)
	(n, m) = (len(A), len(B))
	res = []
	while pos_A < n and pos_B < m:
		(a, b) = (A[pos_A], B[pos_B])
		if a < b:
			res.append(a)
			pos_A += 1
		else:
			res.append(b)
			pos_B += 1
	res += A[pos_A:]
	res += B[pos_B:]
	return res

class UnionFindVerSize:

	def __init__(self, N):
		self._parent = [n for n in range(0, N)]
		self._size = [1] * N
		self.group = N

	def find_root(self, x):
		if self._parent[x] == x:
			return x
		self._parent[x] = self.find_root(self._parent[x])
		stack = [x]
		while self._parent[stack[-1]] != stack[-1]:
			stack.append(self._parent[stack[-1]])
		for v in stack:
			self._parent[v] = stack[-1]
		return self._parent[x]

	def unite(self, x, y):
		gx = self.find_root(x)
		gy = self.find_root(y)
		if gx == gy:
			return
		self.group -= 1
		if self._size[gx] < self._size[gy]:
			self._parent[gx] = gy
			self._size[gy] += self._size[gx]
		else:
			self._parent[gy] = gx
			self._size[gx] += self._size[gy]

	def get_size(self, x):
		return self._size[self.find_root(x)]

	def is_same_group(self, x, y):
		return self.find_root(x) == self.find_root(y)

class WeightedUnionFind:

	def __init__(self, N):
		self.parent = [i for i in range(N)]
		self.size = [1 for i in range(N)]
		self.val = [0 for i in range(N)]
		self.flag = True
		self.edge = [[] for i in range(N)]

	def dfs(self, v, pv):
		stack = [(v, pv)]
		new_parent = self.parent[pv]
		while stack:
			(v, pv) = stack.pop()
			self.parent[v] = new_parent
			for (nv, w) in self.edge[v]:
				if nv != pv:
					self.val[nv] = self.val[v] + w
					stack.append((nv, v))

	def unite(self, x, y, w):
		if not self.flag:
			return
		if self.parent[x] == self.parent[y]:
			self.flag = self.val[x] - self.val[y] == w
			return
		if self.size[self.parent[x]] > self.size[self.parent[y]]:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[x] += self.size[y]
			self.val[y] = self.val[x] - w
			self.dfs(y, x)
		else:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[y] += self.size[x]
			self.val[x] = self.val[y] + w
			self.dfs(x, y)

class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add_edge(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					heapq.heappush(que, (d[e.to], e.to))
		return d

def Z_algorithm(s):
	N = len(s)
	Z_alg = [0] * N
	Z_alg[0] = N
	i = 1
	j = 0
	while i < N:
		while i + j < N and s[j] == s[i + j]:
			j += 1
		Z_alg[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < N and k + Z_alg[k] < j:
			Z_alg[i + k] = Z_alg[k]
			k += 1
		i += k
		j -= k
	return Z_alg

class BIT:

	def __init__(self, n, mod=0):
		self.BIT = [0] * (n + 1)
		self.num = n
		self.mod = mod

	def query(self, idx):
		res_sum = 0
		mod = self.mod
		while idx > 0:
			res_sum += self.BIT[idx]
			if mod:
				res_sum %= mod
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		mod = self.mod
		while idx <= self.num:
			self.BIT[idx] += x
			if mod:
				self.BIT[idx] %= mod
			idx += idx & -idx
		return

class dancinglink:

	def __init__(self, n, debug=False):
		self.n = n
		self.debug = debug
		self._left = [i - 1 for i in range(n)]
		self._right = [i + 1 for i in range(n)]
		self.exist = [True for i in range(n)]

	def pop(self, k):
		if self.debug:
			assert self.exist[k]
		L = self._left[k]
		R = self._right[k]
		if L != -1:
			if R != self.n:
				(self._right[L], self._left[R]) = (R, L)
			else:
				self._right[L] = self.n
		elif R != self.n:
			self._left[R] = -1
		self.exist[k] = False

	def left(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._left[res]
			if res == -1:
				break
			k -= 1
		return res

	def right(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._right[res]
			if res == self.n:
				break
			k -= 1
		return res

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		n = N.bit_length()
		self.table = [[ide_ele for i in range(n)] for i in range(N)]
		self.merge_func = merge_func
		for i in range(N):
			self.table[i][0] = A[i]
		for j in range(1, n):
			for i in range(0, N - 2 ** j + 1):
				f = self.table[i][j - 1]
				s = self.table[i + 2 ** (j - 1)][j - 1]
				self.table[i][j] = self.merge_func(f, s)

	def query(self, s, t):
		b = t - s + 1
		m = b.bit_length() - 1
		return self.merge_func(self.table[s][m], self.table[t - 2 ** m + 1][m])

class BinaryTrie:

	class node:

		def __init__(self, val):
			self.left = None
			self.right = None
			self.max = val

	def __init__(self):
		self.root = self.node(-10 ** 15)

	def append(self, key, val):
		pos = self.root
		for i in range(29, -1, -1):
			pos.max = max(pos.max, val)
			if key >> i & 1:
				if pos.right is None:
					pos.right = self.node(val)
					pos = pos.right
				else:
					pos = pos.right
			elif pos.left is None:
				pos.left = self.node(val)
				pos = pos.left
			else:
				pos = pos.left
		pos.max = max(pos.max, val)

	def search(self, M, xor):
		res = -10 ** 15
		pos = self.root
		for i in range(29, -1, -1):
			if pos is None:
				break
			if M >> i & 1:
				if xor >> i & 1:
					if pos.right:
						res = max(res, pos.right.max)
					pos = pos.left
				else:
					if pos.left:
						res = max(res, pos.left.max)
					pos = pos.right
			elif xor >> i & 1:
				pos = pos.right
			else:
				pos = pos.left
		if pos:
			res = max(res, pos.max)
		return res

def solveequation(edge, ans, n, m):
	x = [0] * m
	used = [False] * n
	for v in range(n):
		if used[v]:
			continue
		y = dfs(v)
		if y != 0:
			return False
	return x

	def dfs(v):
		used[v] = True
		r = ans[v]
		for (to, dire, id) in edge[v]:
			if used[to]:
				continue
			y = dfs(to)
			if dire == -1:
				x[id] = y
			else:
				x[id] = -y
			r += y
		return r

class SegmentTree:

	def __init__(self, init_val, segfunc, ide_ele):
		n = len(init_val)
		self.segfunc = segfunc
		self.ide_ele = ide_ele
		self.num = 1 << (n - 1).bit_length()
		self.tree = [ide_ele] * 2 * self.num
		self.size = n
		for i in range(n):
			self.tree[self.num + i] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.tree[k] = x
		while k > 1:
			self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
			k >>= 1

	def query(self, l, r):
		if r == self.size:
			r = self.num
		res = self.ide_ele
		l += self.num
		r += self.num
		while l < r:
			if l & 1:
				res = self.segfunc(res, self.tree[l])
				l += 1
			if r & 1:
				res = self.segfunc(res, self.tree[r - 1])
			l >>= 1
			r >>= 1
		return res

	def bisect_l(self, l, r, x):
		l += self.num
		r += self.num
		Lmin = -1
		Rmin = -1
		while l < r:
			if l & 1:
				if self.tree[l] <= x and Lmin == -1:
					Lmin = l
				l += 1
			if r & 1:
				if self.tree[r - 1] <= x:
					Rmin = r - 1
			l >>= 1
			r >>= 1
		if Lmin != -1:
			pos = Lmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		elif Rmin != -1:
			pos = Rmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		else:
			return -1
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import gcd, log
input = lambda : sys.stdin.buffer.readline()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
pow_2 = [pow(2, k) for k in range(31)]

def is_include(k, n, m):
	l = n & pow_2[30] - pow_2[k]
	r = l + pow_2[k] - 1
	return 0 <= l <= r <= m

def solve(n, m):
	cnt = 0
	for k in range(30, -1, -1):
		if is_include(k, n, m):
			cnt += pow_2[k]
			n ^= pow_2[k]
	return cnt

def mex(A):
	n = len(A)
	check = [0 for i in range(n + 1)]
	for a in A:
		if a <= n:
			check[a] = 1
	for i in range(n + 1):
		if check[i] == 0:
			return i

def brute(n, m):
	A = [i ^ n for i in range(m + 1)]
	return mex(A)
for _ in range(int(input())):
	(n, m) = mi()
	print(solve(n, m))


from sys import stdin, stdout
import math

def get_list():
	return list(map(int, stdin.readline().strip().split()))

def get_int():
	return int(stdin.readline())

def get_ints():
	return map(int, stdin.readline().strip().split())

def get_string():
	return stdin.readline()

def printn(n):
	stdout.write(str(n) + '\n')

def solve():
	(n, m) = get_ints()
	m += 1
	ans = 0
	for i in range(30, -1, -1):
		if n >= m:
			break
		if n >> i & 1 == m >> i & 1:
			continue
		if m >> i & 1:
			ans |= 1 << i
			n |= 1 << i
	print(ans)
t = get_int()
while t:
	t -= 1
	solve()


import os
import sys
from io import BytesIO, IOBase
_print = print
BUFSIZE = 8192

def dbg(*args, **kwargs):
	_print('\x1b[95m', end='')
	_print(*args, **kwargs)
	_print('\x1b[0m', end='')

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())

def discrete_binary_search(func, lo, hi):
	while lo < hi:
		mi = lo + hi >> 1
		if func(mi):
			hi = mi
		else:
			lo = mi + 1
	return lo

def to_mask(num, size=None) -> list:
	if size is None:
		size = num.bit_length()
	result = [0] * size
	for index in reversed(range(size)):
		if num & 1:
			result[index] = 1
		num >>= 1
	return result

def binary_poly(iterable) -> int:
	result = 0
	for item in iterable:
		result <<= 1
		result += item
	return result

def solve():
	(n, m) = mpint()
	if n > m:
		return 0
	size = m.bit_length() + 1
	ans = []
	for (a, b) in zip(to_mask(n, size=size), to_mask(m + 1, size=size)):
		if a == 0:
			ans.append(b)
		elif b == 0:
			break
		else:
			ans.append(0)
	return binary_poly(ans + [0] * (size - len(ans)))

def main():
	for _ in range(itg()):
		print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1554/problem/C'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		dbg = lambda *args, **kwargs: ...
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG == 3:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	(n, m) = [int(c) for c in input().split()]
	m += 1
	ans = 0
	for i in range(30, -1, -1):
		if n >> i & 1 == m >> i & 1:
			continue
		if n >> i & 1 == 1:
			break
		if n >> i & 1 == 0:
			ans = ans | 1 << i
	print(ans)


for i in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = bin(n)[2:]
	b = bin(m)[2:]
	a = '0' * (32 - len(a)) + a
	b = '0' * (32 - len(b)) + b
	c = ''
	for i in range(32):
		if a[i] == '1' and b[i] == '0':
			c += '0' * (32 - i)
			print(int(c, base=2))
			break
		if a[i] == b[i]:
			c += '0'
		else:
			c += '1'
	else:
		z = 2 ** 32
		c = ''
		for i in range(32):
			if a[i] == '0' and b[i] == '0':
				z = min(z, int(c + '1' + '0' * (31 - i), base=2))
			if a[i] == b[i]:
				c += '0'
			else:
				c += '1'
		print(z)


def f(n, m, ind):
	if n >= m:
		return 0
	if ind < 0:
		return 0
	if n >> ind & 1 == m >> ind & 1:
		return f(n, m, ind - 1)
	else:
		return f(n | 1 << ind, m, ind - 1) | 1 << ind
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	print(f(n, m + 1, len(bin(m + 1)) - 2))


import sys
import math
import heapq
from collections import defaultdict as dd
from collections import OrderedDict as od
from collections import deque
from itertools import permutations as pp
from itertools import combinations as cc
from sys import stdin
from functools import cmp_to_key
from functools import lru_cache
from bisect import bisect_left as bs_l
from bisect import bisect_right as bs_r
input = sys.stdin.readline
mod = 10 ** 9 + 7
sys.setrecursionlimit(10 ** 5)
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for i in range(32, -1, -1):
		(bit1, bit2) = (n & 1 << i, m & 1 << i)
		if bit1 > bit2:
			break
		elif bit1 < bit2:
			ans |= 1 << i
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	st = 1 << 30
	while n < m and st:
		if not st & n and st & m:
			ans += st
			n += st
		st >>= 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	k = 2 ** 31
	ans = 0
	while k:
		if k > m + 1:
			if k <= n:
				break
			else:
				pass
		elif k == m + 1:
			if k <= n:
				break
			else:
				ans += k
				break
		elif k <= n:
			n %= k
			m %= k
		else:
			ans += k
			n %= k
			m %= k
		k //= 2
	print(ans)


from random import randint

def mysolve(N, M):
	N = bin(N)[2:]
	M = bin(M)[2:]
	while len(N) < len(M):
		N = '0' + N
	while len(N) > len(M):
		M = '0' + N
	ans = ['' for _ in range(50)]
	flag = False
	for i in range(len(N)):
		if flag:
			ans[i + 1] = '0'
			continue
		if N[i] == M[i]:
			ans[i + 1] = '0'
		elif M[i] == '1':
			ans[i + 1] = '1'
		else:
			ans[i + 1] = '0'
			flag = True
	if not flag:
		i = len(N) - 1
		while M[i] == '1' and i >= 0:
			ans[i + 1] = '0'
			i = i - 1
		ans[i + 1] = '1'
		return int(''.join(ans), 2)
	else:
		return int(''.join(ans), 2)

def othersolve(n, m):
	s = set(list(range(10000)))
	for i in range(m + 1):
		s.remove(n ^ i)
	print(bin(n))
	print(bin(m))
	print(bin(min(s)))
	return min(s)
T = int(input())
for _ in range(T):
	(N, M) = list(map(int, input().split()))
	print(mysolve(N, M))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	if m < n:
		print(0)
	else:
		sn = ''
		sm = ''
		nn = n
		mm = m + 1
		ans = ''
		an = 0
		while nn > 0:
			sn += str(nn % 2)
			nn //= 2
		while mm > 0:
			sm += str(mm % 2)
			mm //= 2
		for _ in range(len(sm) - len(sn)):
			sn += '0'
		sn = sn[::-1]
		sm = sm[::-1]
		mm = len(sm)
		if 2 ** mm - 1 == m:
			print(2 ** mm)
		else:
			sb = '1' * mm
			for i in range(mm):
				if sb[i] == sm[i] and an <= m:
					ans += sb[i]
				else:
					ans += sn[i]
				an += int(ans[i]) * 2 ** (mm - 1 - i)
			ans = ans[::-1]
			print(an ^ n)


import sys
from math import *
import builtins
import string
import bisect
alphabets = list(string.ascii_lowercase)
ALPHABETS = list(string.ascii_uppercase)

def print(x, end='\n'):
	sys.stdout.write(str(x) + end)

def get_int():
	return int(input())

def get_list_ints():
	return list(map(int, input().split()))

def get_char_list():
	s = input()
	return list(s[:len(s)])

def get_tuple_ints():
	return tuple(map(int, input().split()))

def print_iterable(p):
	print(' '.join(map(str, p)))

def floorSearch(arr, low, high, x):
	if low > high:
		return -1
	if x >= arr[high]:
		return high
	mid = int((low + high) / 2)
	if arr[mid] == x:
		return mid
	if mid > 0 and arr[mid - 1] <= x < arr[mid]:
		return mid - 1
	if x < arr[mid]:
		return floorSearch(arr, low, mid - 1, x)
	return floorSearch(arr, mid + 1, high, x)

def binary_search(arr, x):
	low = 0
	high = len(arr) - 1
	mid = 0
	while low <= high:
		mid = (high + low) // 2
		if arr[mid] < x:
			low = mid + 1
		elif arr[mid] > x:
			high = mid - 1
		else:
			return mid
	return high

def main():
	p = get_int()
	for q in range(p):
		(n, m) = get_list_ints()
		ans = 0
		m += 1
		for k in range(30, -1, -1):
			if n >= m:
				break
			if n >> k & 1 == m >> k & 1:
				pass
			elif m >> k & 1 == 1:
				ans |= 1 << k
				n |= 1 << k
				m |= 1 << k
		print(ans)
	pass
main()


def f(n, m):
	ans = 0
	m += 1
	for i in range(30, -1, -1):
		if n >= m:
			break
		if n & 1 << i == m & 1 << i:
			continue
		if m & 1 << i:
			ans += 1 << i
			n += 1 << i
	return ans
for _ in range(int(input())):
	(a, b) = map(int, input().strip().split())
	print(f(a, b))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = 0
	for i in range(31, -1, -1):
		x = 1 << i
		a = x & n
		b = x & m + 1
		if a == 0:
			if b == 0:
				continue
			else:
				ans |= x
		if a == x:
			if b == 0:
				break
			else:
				continue
	print(ans)


import sys, os
from math import *
from bisect import *
from heapq import *
from collections import *
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, m) = MI()
		if m < n:
			print(0)
			continue
		m += 1
		(out, bit) = (0, 31)
		while bit >= 0:
			if n & 1 << bit and m & 1 << bit == 0:
				break
			if n & 1 << bit == 0 and m & 1 << bit:
				out |= 1 << bit
			bit -= 1
		print(out)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def MI():
	return map(int, input().split())

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


import sys
input = lambda : sys.stdin.readline().rstrip()

def driver():
	T = int(input())
	for _ in range(T):
		(a, b) = [int(g) for g in input().split()]
		b += 1
		result = 0
		for i in range(30, -1, -1):
			if a < b:
				if a >> i & 1 == b >> i & 1:
					continue
				if b >> i & 1 == 1:
					result |= 1 << i
					a |= 1 << i
		print(result)
driver()


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	res = 0
	(n, m) = map(int, input().split())
	m += 1
	for i in range(30, -1, -1):
		if n >> i & 1 == m >> i & 1:
			continue
		if m >> i & 1:
			res |= 1 << i
			n |= 1 << i
		if n >= m:
			break
	print(res)


def ans(n, m):
	a = bin(n)[2:]
	b = bin(m + 1)[2:]
	x = len(a)
	y = len(b)
	a = '0' * (max(x, y) - len(a)) + a
	b = '0' * (max(x, y) - len(b)) + b
	an = ''
	f = 0
	for i in range(max(x, y)):
		if f == 1:
			an = an + '0'
		elif a[i] == '0':
			if b[i] == '0':
				an = an + '0'
			else:
				an = an + '1'
		elif b[i] == '0':
			f = 1
			an = an + '0'
		else:
			an = an + '0'
	answer = int(an, 2)
	return answer
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	print(ans(n, m))


import sys
import math
import random
from queue import PriorityQueue as PQ
from bisect import bisect_left as BSL
from bisect import bisect_right as BSR
from collections import OrderedDict as OD
from collections import Counter
from itertools import permutations
mod = 1000000007
MOD = mod
try:
	sys.stdin = open('actext.txt', 'r')
	OPENFILE = 1
except:
	pass

def get_ints():
	return map(int, input().split())

def palindrome(s):
	mid = len(s) // 2
	for i in range(mid):
		if s[i] != s[len(s) - i - 1]:
			return False
	return True

def check(i, n):
	if 0 <= i < n:
		return True
	else:
		return False
t = int(input())
for tt in range(t):
	(n, k) = get_ints()
	n = '{:032b}'.format(n)
	k = '{:032b}'.format(k + 1)
	s = ''
	for i in range(32):
		if k[i] == '1' and n[i] == '1':
			s += '0'
		elif k[i] == '1':
			s += '1'
		elif n[i] == '1':
			break
		else:
			s += '0'
	s = s + '0' * (32 - len(s))
	print(int(s, 2))


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	if m < n:
		print(0)
	else:
		m += 1
		n_b = list(bin(n)[2:])
		m_b = list(bin(m)[2:])
		n_b = ['0'] * (30 - len(n_b)) + n_b
		m_b = ['0'] * (30 - len(m_b)) + m_b
		msb = -1
		for i in range(0, len(n_b)):
			if n_b[i] == '1' and m_b[i] != '1':
				msb = i
				break
		if msb == -1:
			print(int(''.join(m_b), 2) ^ int(''.join(n_b), 2))
		else:
			for i in range(msb, len(n_b)):
				if n_b[i] == '1':
					m_b[i] = '1'
				else:
					m_b[i] = '0'
			print(int(''.join(m_b), 2) ^ int(''.join(n_b), 2))


import sys

def mapInt():
	return map(int, input().split())

def code_init():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve(n, m):
	m += 1
	ans = 0
	for i in range(30, -1, -1):
		if n >= m:
			break
		if n >> i & 1 == m >> i & 1:
			continue
		if m >> i & 1:
			ans |= 1 << i
			n |= 1 << i
	return ans

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = mapInt()
		res = solve(n, m)
		print(res)
main()


for testis in range(int(input())):
	(n, m) = map(int, input().split())
	if m < n:
		print(0)
	else:
		m = bin(m + 1)[2:]
		n = '0' * (len(m) - len(bin(n)[2:])) + bin(n)[2:]
		ans = ['0'] * len(m)
		for i in range(len(m)):
			if n[i] == m[i]:
				ans[i] = '0'
			elif n[i] == '1' and m[i] == '0':
				break
			else:
				ans[i] = '1'
		print(int(''.join(ans), 2))


from itertools import permutations
import itertools
from collections import Counter
from fractions import Fraction
from collections import defaultdict
import math
import os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for k in range(30, -1, -1):
		if n >= m:
			break
		if n >> k & 1 == m >> k & 1:
			continue
		if m >> k & 1:
			ans |= 1 << k
			n |= 1 << k
	print(ans)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
sys.setrecursionlimit(111111)
INF = 999999999999999999999999
alphabets = 'abcdefghijklmnopqrstuvwxyz'

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

class SegTree:

	def __init__(self, n):
		self.N = 1 << n.bit_length()
		self.tree = [0] * (self.N << 1)

	def update(self, i, j, v):
		i += self.N
		j += self.N
		while i <= j:
			if i % 2 == 1:
				self.tree[i] += v
			if j % 2 == 0:
				self.tree[j] += v
			(i, j) = (i + 1 >> 1, j - 1 >> 1)

	def query(self, i):
		v = 0
		i += self.N
		while i > 0:
			v += self.tree[i]
			i >>= 1
		return v

def SieveOfEratosthenes(limit):
	isPrime = [True] * (limit + 1)
	isPrime[0] = isPrime[1] = False
	primes = []
	for i in range(2, limit + 1):
		if not isPrime[i]:
			continue
		primes += [i]
		for j in range(i * i, limit + 1, i):
			isPrime[j] = False
	return primes

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = ri()
	for _ in range(tc):
		(n, m) = ria()
		N = n
		M = m + 1
		ans = 0
		for i in range(30, -1, -1):
			if 1 << i & N != 1 << i & M:
				if 1 << i & N:
					break
				else:
					ans += 1 << i
		wi(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from pickle import TRUE
import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def getHighestBitValue(v):
	return 1 << v.bit_length() - 1

def getPaddedBitString(v, bitStringLength):
	bitString = '{0:b}'.format(v)
	while len(bitString) < bitStringLength:
		bitString = '0' + bitString
	return bitString

def bruteforce(n, m):
	values = set()
	for i in range(m + 1):
		values.add(n ^ i)
	for i in range(m + 2):
		if i not in values:
			return i
	return None

def getAnswer(n, m):
	if n == 0:
		return m + 1
	if m == 0:
		return 0
	highestNBit = getHighestBitValue(n)
	if highestNBit > m:
		return 0
	bitOn = getHighestBitValue(m)
	answerValue = m
	foundGap = False
	hitOne = False
	hadZerosAfterHitOne = False
	while bitOn > 0:
		bitOnInN = bitOn & n > 0
		bitOnInM = bitOn & m > 0
		restOfBitsOnInM = bitOn - 1 & m == bitOn - 1
		if hitOne and bitOnInM and hadZerosAfterHitOne and restOfBitsOnInM:
			answerValue |= bitOn << 1
			answerValue &= ~((bitOn << 1) - 1)
			foundGap = True
			break
		if hitOne and (not bitOnInM) and (not bitOnInN):
			hadZerosAfterHitOne = True
		if bitOnInN:
			hitOne = True
			if bitOnInM:
				answerValue &= ~bitOn
				hadZerosAfterHitOne = False
			else:
				answerValue &= ~(bitOn - 1)
				foundGap = True
				break
		bitOn >>= 1
	if foundGap:
		return answerValue
	if hadZerosAfterHitOne:
		return answerValue + 1
	return m + 1

def debug(n, m, answer):
	bitStringLength = max(n.bit_length(), m.bit_length(), answer.bit_length())
	print(getPaddedBitString(n, bitStringLength))
	print(getPaddedBitString(m, bitStringLength))
	print(getPaddedBitString(answer, bitStringLength))
	print()

def testValues(n, m):
	bfAnswer = bruteforce(n, m)
	answer = getAnswer(n, m)
	if bfAnswer is None:
		print('bf answer is none for %d %d' % (n, m))
	if bfAnswer != answer:
		debug(n, m, bfAnswer)
		print('Answers do not match for n=%d, m=%d, answer=%d, bfAnswer=%d' % (n, m, answer, bfAnswer))
		return False
	print('Answer (%d) is correct for n=%d, m=%d' % (answer, n, m))
	return True

def main():
	numTestCases = int(input())
	for _ in range(numTestCases):
		(n, m) = invr()
		answer = getAnswer(n, m)
		print(answer)
main()


import sys
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, sys.stdin.readline().strip().split()))
	if n > m:
		print(0)
	else:
		bin_n = list(map(int, bin(n)[:1:-1]))
		bin_m = list(map(int, bin(m)[:1:-1]))
		bin_m.append(0)
		changeable = []
		min_diff = m - n
		diff_now = 0
		for pos in range(len(bin_m)):
			if pos < len(bin_n) and bin_n[pos] == 0:
				changeable.append(2 ** pos)
				diff_now += changeable[-1]
			elif pos >= len(bin_n):
				changeable.append(2 ** pos)
				diff_now += changeable[-1]
			if diff_now > min_diff:
				break
		for c in changeable[::-1]:
			if diff_now - c > min_diff:
				diff_now -= c
		print(diff_now)


import math
from sys import stdin, stdout
from collections import defaultdict as df, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	if n > m:
		print(0)
	elif n == 0:
		print(m + 1)
	else:
		m = m + 1
		mex = 0
		cnt = 32
		while cnt > -1:
			a = n & 1 << cnt
			b = m & 1 << cnt
			if a < b:
				mex += b
			if b < a:
				break
			cnt -= 1
		print(mex)


import sys
input = sys.stdin.readline

def fun(n, m):
	nbin = bin(n)[2:]
	mbin = bin(m + 1)[2:]
	k = ''
	if len(nbin) > len(mbin):
		return 0
	elif len(mbin) > len(nbin):
		idx = len(mbin) - len(nbin)
		k = mbin[:idx]
		nbin = ''.join(['0'] * (len(mbin) - len(nbin))) + nbin
	else:
		idx = 0
	while idx < len(nbin):
		if nbin[idx] == mbin[idx]:
			k += '0'
		elif nbin[idx] == '0' and mbin[idx] == '1':
			k += '1'
		else:
			k = k + ''.join(['0'] * (len(nbin) - idx))
			break
		idx += 1
	return int(k, 2)
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	print(fun(n, m))


import queue

def TestCase():
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for k in range(30, -1, -1):
		if n >= m:
			break
		if n >> k & 1 == m >> k & 1:
			continue
		if m >> k & 1:
			ans |= 1 << k
		else:
			break
	print(ans)
t = int(input())
for _ in range(t):
	TestCase()


import typing

def solve(n: int, m: int) -> typing.NoReturn:
	t = m + 1
	l = t.bit_length()
	k = 0
	for i in range(l - 1, -1, -1):
		if n ^ k >= t:
			break
		if ~t >> i & 1:
			continue
		k |= (1 << i) * (n >> i & 1 ^ 1)
	print(k)

def main() -> typing.NoReturn:
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		solve(n, m)
main()


import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque, defaultdict
from functools import lru_cache, reduce
from heapq import heappush, heappop, heapify, heappushpop, _heappop_max, _heapify_max

def _heappush_max(heap, item):
	heap.append(item)
	heapq._siftdown_max(heap, 0, len(heap) - 1)

def _heappushpop_max(heap, item):
	if heap and item < heap[0]:
		(item, heap[0]) = (heap[0], item)
		heapq._siftup_max(heap, 0)
	return item
from math import gcd as GCD, modf
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
t = int(readline())
for _ in range(t):
	(N, M) = map(int, readline().split())
	M += 1
	flag = True
	ans = 0
	for i in range(31, -1, -1):
		if not N >> i & 1 and M >> i & 1 and flag:
			ans ^= 1 << i
		if flag and N >> i & 1 and (not M >> i & 1):
			flag = False
	print(ans)


def solve():
	(n, m) = map(int, input().split())
	if n > m:
		return 0
	if n | m == m:
		return n ^ (n | m + 1)
	bm = bin(m)[2:]
	bn = bin(n)[2:]
	bn = '0' * (len(bm) - len(bn)) + bn
	to_transform = list(bn)
	for i in range(len(to_transform)):
		if to_transform[i] == '1' and bm[i] == '0':
			break
		elif to_transform[i] == '0' and bm[i] == '1':
			to_transform[i] = bm[i]
	ans = n ^ (n | int(''.join(to_transform), 2))
	return ans
t = int(input())
for _ in range(t):
	print(solve())


from sys import stdout
from sys import stdin

def get():
	return stdin.readline().strip()

def getf(sp=' '):
	return [int(i) for i in get().split(sp)]

def put(a, end='\n'):
	stdout.write(str(a) + end)

def putf(a, sep=' ', end='\n'):
	stdout.write(sep.join([str(i) for i in a]) + end)

def solve(n, m):
	if n > m:
		return 0
	a = [0] + [int(i) for i in bin(m)[2:]]
	b = [0] + [int(i) for i in bin(n)[2:]]
	k = len(a)
	b = [0] * (k - len(b)) + b
	x = 10 ** 12
	for i in range(k):
		if a[i] == 0:
			a1 = a.copy()
			a1[i] = 1
			for j in range(i + 1, k):
				a1[j] = b[j]
			num_a = int(''.join([str(j) for j in a1]), 2)
			x = min(x, num_a ^ n)
	return x

def main():
	for _ in range(int(get())):
		(n, m) = getf()
		put(solve(n, m))
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	c = bin(n)[2:]
	d = '0' + bin(k)[2:]
	c = '0' * (len(d) - len(c)) + c
	ans = 0
	for i in range(len(d)):
		if d[i] == '1' and c[i] == '0':
			ans += 1 << len(d) - i - 1
		elif '1' * (len(d) - i - 1) == d[i + 1:] and c[i] == '0':
			ans += 1 << len(d) - i - 1
			break
		elif d[i] == '0' and c[i] == '1':
			break
	print(ans)


import sys
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	if n > m:
		print(0)
		return
	for i in range(31):
		c = 1 << i
		if c > n and c > m:
			r = 0
			for j in range(i, -1, -1):
				if n ^ r > m:
					print(r)
					break
				if n ^ r | (1 << j + 1) - 1 <= m:
					r ^= 1 << j + 1
					print(r)
					return
				if m & 1 << j != 0:
					if n & 1 << j == 0:
						r |= 1 << j
						if n ^ r > m:
							print(r)
							return
			if n ^ r <= m:
				r ^= 1
				print(r)
				return
			print(r)
			break
for i in range(int(input())):
	solve()


import sys
input = sys.stdin.buffer.readline

def f(n, m, i):
	if i < 0:
		return 0
	if i == 0:
		if m & 1:
			return 2
		elif n & 1:
			return 0
		else:
			return 1
	if n >> i & 1:
		if m >> i & 1:
			x = f(n, m, i - 1)
			if x == 1 << i:
				return 1 << i + 1
			else:
				return x
		else:
			return 0
	elif m >> i & 1:
		x = f(n, m, i - 1)
		return (1 << i) + x
	else:
		return f(n, m, i - 1)
for t in range(int(input())):
	(N, M) = map(int, input().split())
	print(f(N, M, 31))


t = int(input())
for xx in range(t):
	[n, m] = [int(x) for x in input().split()]
	i = 0
	ans = 0
	m += 1
	bitn = []
	bitm = []
	while n > 0 or m > 0:
		bitn.append(n % 2)
		bitm.append(m % 2)
		n = n // 2
		m = m // 2
	bitm.reverse()
	bitn.reverse()
	control = 0
	ans = 0
	for i in range(len(bitn)):
		if control == 1:
			ans *= 2
		elif bitn[i] == 1 and bitm[i] == 1:
			ans *= 2
		elif bitn[i] == 0 and bitm[i] == 1:
			ans = 2 * ans + 1
		elif bitn[i] == 1 and bitm[i] == 0:
			ans = 2 * ans
			control = 1
		else:
			ans = 2 * ans
	print(ans)


import sys
input = sys.stdin.buffer.readline
T = int(input())
while T:
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for i in range(30, -1, -1):
		if n >= m:
			break
		elif n >> i & 1 == m >> i & 1:
			continue
		elif m >> i & 1:
			ans |= 1 << i
			n |= 1 << i
	print(ans)
	T -= 1


import sys, os, io
from sys import stdin
import math
from collections import defaultdict
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
alphabets = list('abcdefghijklmnopqrstuvwxyz')
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	(n, m) = li()
	if m < n:
		print(0)
		return
	m += 1
	n = list(bin(n)[2:])
	m = list(bin(m)[2:])
	x = max(len(n), len(m))
	if len(n) < x:
		n = ['0'] * (x - len(n)) + n
	else:
		m = ['0'] * (x - len(m)) + m
	ans = []
	for i in range(len(n)):
		if n[i] == m[i]:
			ans.append('0')
		elif n[i] == '0' and m[i] == '1':
			ans.append('1')
		else:
			break
	ans = ans + ['0'] * (len(n) - len(ans))
	ans = ''.join(ans)
	print(int(ans, 2))
t = 1
t = ii()
for _ in range(t):
	solve()


from functools import lru_cache
from itertools import count

def solve():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		m += 1
		ans = 0
		for i in range(30, -1, -1):
			if n >= m:
				break
			if m >> i & 1 == n >> i & 1:
				continue
			if m >> i & 1 == 1:
				ans |= 1 << i
				n |= 1 << i
		print(ans)
solve()


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ans = 0
	flg = 0
	for i in range(34, -1, -1):
		if n & 1 << i and (not m & 1 << i):
			flg = 1
		elif not n & 1 << i and (not m & 1 << i):
			continue
		elif n & 1 << i and m & 1 << i:
			continue
		elif not flg:
			ans += 1 << i
	if not flg:
		for i in range(35):
			if not n & 1 << i and (not m & 1 << i):
				ans += 1 << i
				for j in range(i):
					if not n & 1 << j and m & 1 << j:
						ans -= 1 << j
				break
	print(ans)


def solve(n, m):
	if n > m:
		return 0
	nbin = '{0:032b}'.format(n)
	mbin = '{0:032b}'.format(m)
	used = []
	free = []
	for i in reversed(range(len(mbin))):
		if nbin[31 - i] == '1':
			used.append(2 ** i)
		else:
			free.append(2 ** i)
	left = m - n + 1
	tmp = 0
	tot_sum = sum(free)
	for i in range(len(free)):
		if tot_sum - free[i] + tmp < left:
			tmp += free[i]
		tot_sum -= free[i]
	return tmp
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input().decode().strip())
for t in range(T):
	(n, k) = [int(x) for x in input().decode().strip().split(' ')]
	res = solve(n, k)
	print(res)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def LI1():
	return list(map(int1, sys.stdin.readline().split()))

def LLI1(rows_number):
	return [LI1() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline().rstrip()
inf = 10 ** 16
md = 10 ** 9 + 7

def solve():
	(n, m) = LI()
	if n > m:
		print(0)
		return
	ans = n ^ m
	cur = ans & n
	if cur:
		i = cur.bit_length()
		ans = ans >> i << i
	else:
		for i in range(32):
			if ans >> i & 1 == 0 and n >> i & 1 == 0:
				ans = ans >> i << i
				ans |= 1 << i
				break
	print(ans)
for testcase in range(II()):
	solve()


from itertools import permutations
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 * 10 ** 9, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	(n, m) = map(int, input().split())
	if m < n:
		print(0)
		continue
	fi = 2 * 10 ** 9
	ans = 0
	for j in range(31, -1, -1):
		if m & 1 << j > 0 and n & 1 << j == 0:
			ans += 1 << j
		elif n & 1 << j > 0 and m & 1 << j == 0:
			fi = min(fi, ans)
			break
		elif n & 1 << j == 0 and m & 1 << j == 0:
			fi = min(fi, ans + (1 << j))
	print(fi)


def read_line():
	return [int(x) for x in input().split()]

def read_int():
	return int(input())

def solve():
	(n, m) = read_line()
	m += 1
	res = 0
	for i in range(30, -1, -1):
		bit = 1 << i
		if n & bit != 0 and m & bit == 0:
			break
		if n & bit == 0 and m & bit != 0:
			res = res | bit
	print(res)
t = read_int()
while t > 0:
	solve()
	t -= 1


def solve(n, m):
	if m < n:
		return 0
	M = bin(m)[2:]
	N = bin(n)[2:]
	N = '0' * (len(M) - len(N)) + N
	ans = []
	nstart = -1
	lastmzero = -1
	for (i, (mc, nc)) in enumerate(zip(M, N)):
		if nc == '1' and nstart < 0:
			nstart = i
		if nstart < 0:
			ans.append(mc)
		elif mc == '1' and nc == '1':
			ans.append('0')
		elif mc == '1' and nc == '0':
			ans.append('1')
		elif mc == '0' and nc == '0':
			ans.append('0')
		else:
			return int(''.join(ans) + '0' * (len(M) - i), base=2)
		if mc == '0':
			lastmzero = i
	if lastmzero >= 0:
		return int(''.join(ans[:lastmzero]) + '1' + '0' * (len(M) - 1 - lastmzero), base=2)
	return m + 1
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	print(solve(n, m))


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(iinp()):
	(n, m) = mp()
	x = m + 1
	ans = 0
	i = 30
	while i >= 0 and n < x:
		if n & 1 << i != x & 1 << i:
			if x & 1 << i:
				ans |= 1 << i
				n |= 1 << i
		i -= 1
	print(ans)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	mex = 0
	m += 1
	z = 1 << 30
	while z and n < m:
		if not z & n and z & m:
			mex += z
			n += z
		z >>= 1
	print(mex)


t = int(input())
for _ in range(t):
	res = 0
	(n, m) = map(int, input().split())
	m += 1
	for i in range(30, -1, -1):
		if n >> i & 1 == m >> i & 1:
			continue
		if m >> i & 1:
			res |= 1 << i
			n |= 1 << i
		if n >= m:
			break
	print(res)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	if m < n:
		print(0)
		continue
	ans = 0
	for pos in range(30, -1, -1):
		bitn = n & 1 << pos > 0
		bitm = m + 1 & 1 << pos > 0
		if bitn == bitm:
			continue
		elif bitn == 1 and bitm == 0:
			break
		elif bitn == 0 and bitm == 1:
			ans += 1 << pos
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, m) = map(int, input().split())
	if m < n:
		print(0)
		continue
	x = 0
	for i in range(32, -1, -1):
		if n & 1 << i == 0:
			if m & 1 << i != 0:
				x |= 1 << i
		elif m & 1 << i == 0:
			break
	if x ^ n <= m:
		for i in range(32):
			if n ^ (x | 1 << i) > m:
				x |= 1 << i
				for j in range(i - 1, -1, -1):
					if x & 1 << j != 0:
						x ^= 1 << j
				break
	print(x)


import sys
input = sys.stdin.buffer.readline

def solve_tc():
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for k in range(30, -1, -1):
		if n >= m:
			break
		l = m >> k & 1
		if l and l != n >> k & 1:
			ans |= 1 << k
			n |= 1 << k
	return ans
t = int(input())
for _ in range(t):
	sys.stdout.write(str(solve_tc()) + '\n')


import sys
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def li():
	return [int(i) for i in input().split()]

def lli(rows):
	return [li() for _ in range(rows)]

def si():
	return input()

def ii():
	return int(input())

def ins():
	return input().split()

def solve(n, m):
	s = 0
	(util, pre) = ([], [])
	for i in range(31):
		if n & 1 << i == 0:
			s += 1 << i
			util.append(i)
			pre.append(s)
	diff = max(0, m - n + 1)
	ans = 0
	while diff > 0:
		for i in range(len(util)):
			if pre[i] >= diff:
				ans |= 1 << util[i]
				diff -= 1 << util[i]
				break
	return ans
t = II()
for _ in range(t):
	(n, m) = MI()
	print(solve(n, m))


import sys
import math
from math import *
import builtins
import collections
import bisect
import os
from io import BytesIO, IOBase

def print(x, end='\n'):
	sys.stdout.write(str(x) + end)

def get_int():
	return int(input())

def get_list_ints():
	return list(map(int, input().split()))

def get_char_list():
	s = input()
	return list(s[:len(s) - 1])

def get_tuple_ints():
	return tuple(map(int, input().split()))

def print_iterable(p):
	print(' '.join(map(str, p)))

def CountFrequency(arr):
	return collections.Counter(arr)

def reverse(s):
	l = len(s)
	for i in range(l // 2):
		(s[i], s[l - i - 1]) = (s[l - i - 1], s[i])
	return s

def binary_search(arr, x):
	low = 0
	high = len(arr) - 1
	mid = 0
	while low <= high:
		mid = (high + low) // 2
		if arr[mid] < x:
			low = mid + 1
		elif arr[mid] > x:
			high = mid - 1
		else:
			return mid
	return high

def lower_bound(arr, x):
	return bisect.bisect_left(arr, x, lo=0, hi=len(arr))

def upper_bound(arr, x):
	return bisect.bisect_right(arr, x, lo=0, hi=len(arr))

def pow(a, n):
	if n == 0:
		return 1
	elif n % 2 == 0:
		return pow(a, n // 2) % const * (pow(a, n // 2) % const) % const
	else:
		return pow(a, n // 2) % const * (pow(a, n // 2) % const) * (a % const) % const

def operate(v, w):
	ans = 0
	if v >= w:
		return 0
	else:
		for i in range(31, -1, -1):
			k = v >> i
			l = w >> i
			if v >= w:
				break
			if k & 1 == 1 and l & 1 == 1:
				continue
			elif k & 1 == 0 and l & 1 == 0:
				continue
			elif l & 1 == 1:
				ans |= 1 << i
				v |= 1 << i
		return ans

def main():
	n = get_int()
	for i in range(n):
		[n, m] = get_list_ints()
		print(operate(n, m + 1))
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def solve(n, m):
	if n > m:
		print(0)
		return
	d = (1 << 35) - 1
	i = 40
	while i > -1:
		dd = d - (1 << i)
		if dd > m and dd & n == n:
			d = dd
		i -= 1
	print(n ^ d)
t = int(input())
for i in range(t):
	(n, m) = [int(j) for j in input().split()]
	solve(n, m)


def bit(n):
	res = []
	while n:
		res.append(n % 2)
		n //= 2
	return res

def tod(s):
	res = 0
	cur = 1
	for i in range(len(s)):
		res += s[i] * cur
		cur *= 2
	return res
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	q = bit(n)
	w = bit(m)
	res = w[:]
	if m < n:
		print(0)
		continue
	ans = [0 for _ in range(len(q))] + w[len(q):]
	pr = False
	for i in range(len(q) - 1, -1, -1):
		if q[i] == 1 and w[i] == 0:
			pr = True
			break
		if q[i] == 0 and w[i] == 1:
			ans[i] = 1
	if not pr:
		for i in range(len(ans)):
			if i < len(q):
				if ans[i] == 0 and q[i] == 0:
					ans[i] = 1
					for j in range(i - 1, -1, -1):
						ans[j] = 0
					break
			elif ans[i] == 0:
				ans[i] = 1
				for j in range(i - 1, -1, -1):
					ans[j] = 0
				break
		else:
			ans = [0 for _ in range(len(ans))] + [1]
	ans = tod(ans)
	print(ans)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	if m < n:
		print(0)
		continue
	bn = bin(n)[2:][::-1]
	bm = bin(m + 1)[2:][::-1]
	a = []
	for i in range(len(bn)):
		if bm[i] == '1' and bn[i] == '0':
			a.append(i)
	for i in range(len(bn), len(bm)):
		if bm[i] == '1':
			a.append(i)
	ans = 0
	a.reverse()
	for i in a:
		ans |= 1 << i
		if ans | n > m:
			break
	print(ans)


t = int(input())
for tc in range(t):
	(n, m) = map(int, input().split())
	m += 1
	target = '0' * max(len(bin(n)[2:]) - len(bin(m)[2:]), 0) + bin(m)[2:]
	current = '0' * max(len(bin(m)[2:]) - len(bin(n)[2:]), 0) + bin(n)[2:]
	bink = '0b'
	for i in range(len(current)):
		if current[i] == target[i]:
			bink += '0'
		elif current[i] == '0' and target[i] == '1':
			bink += '1'
		elif current[i] == '1' and target[i] == '0':
			break
	bink += '0' * (len(current) - (len(bink) - 2))
	print(int(bink, 2))


n_testcase = int(input())
for testcase in range(n_testcase):
	(n, m) = (int(x) for x in input().split())
	m += 1
	n2 = 1
	while n2 <= n:
		n2 <<= 1
	answer = m // n2 * n2
	m %= n2
	n2 >>= 1
	while n2 >= 1:
		if n & n2 == n2:
			m = max(m - n2, 0)
		elif m >= n2:
			answer += n2
			m -= n2
		n2 >>= 1
	print(answer)


from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from math import ceil, floor, log, sqrt
from collections import Counter, deque
from heapq import heappush, heappop, heapify
from itertools import permutations, product

def re():
	return stdin.readline().rstrip()

def mapi():
	return map(int, re().split())

def veci():
	return list(map(int, re().split()))
mod = 1000000007

def solve(n, m):
	ans = 0
	for i in range(32, -1, -1):
		if n >= m:
			break
		if m >> i & 1 and (not n >> i & 1):
			n |= 1 << i
			ans |= 1 << i
	return ans
for t in range(int(re())):
	(n, m) = mapi()
	print(solve(n, m + 1))


import sys
input = sys.stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())

def check(n, i):
	return n >> i & 1

def solve():
	(n, m) = R()
	if m < n:
		print(0)
		return
	ans = 0
	m += 1
	for i in range(30, -1, -1):
		if True == check(n, i) and False == check(m, i):
			break
		elif False == check(n, i) and True == check(m, i):
			ans |= 1 << i
	print(ans)
	return
for _ in range(I()):
	solve()


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]
INF = 10 ** 10

def solve(N, M):
	if N > M:
		return 0
	ans = 0
	for i in reversed(range((M + 1).bit_length())):
		n_i = (N & 1 << i) >> i
		m_i = (M + 1 & 1 << i) >> i
		if (n_i, m_i) == (1, 0):
			return ans
		elif (n_i, m_i) == (0, 1):
			ans |= 1 << i
	return ans
T0 = int(input())
for _ in range(T0):
	(N, M) = map(int, input().split())
	print(solve(N, M))


tcase = int(input().strip())
for _ in range(tcase):
	(n, m) = map(int, input().strip().split())
	if n > m:
		print(0)
	else:
		ans = 0
		m += 1
		for pos in range(30, -1, -1):
			if n >> pos & 1 == m >> pos & 1:
				continue
			elif n >> pos & 1:
				break
			else:
				ans |= 1 << pos
		print(ans)


import sys
input = sys.stdin.readline

def I():
	return input().strip()

def II():
	return int(input().strip())

def LI():
	return [*map(int, input().strip().split())]
import copy, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, combinations, groupby
from operator import itemgetter
for _ in range(II()):
	(a, b) = LI()
	if a > b:
		print(0)
		continue
	get_bin = lambda x, n: format(x, 'b').zfill(n)
	(A, B) = (get_bin(a, 32), get_bin(b + 1, 32))
	ans = [0] * 32
	for i in range(32):
		if A[i] == B[i]:
			continue
		if A[i] == '1':
			break
		ans[i] = 1
	print(int(''.join([str(x) for x in ans]), 2))


import sys
import bisect
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
sflo = lambda : list(map(float, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
mod1 = 998244353
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs2(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)
ans = 0
b = []
vis = []
tot = 0
time = []
time1 = []
adj = []
mx = -1
eps = 1e-07

def dfs(a, b, p, c):
	if a == b:
		return c
	for (i, j) in adj[a]:
		if i == p:
			continue
		temp = dfs(i, b, a, c + j)
		if dfs(i, b, a):
			mx = max(i, mx)
			return 1
adj = []
ans = []

def dfs(root, par, v):
	global adj, ans, abe
	tot = v
	for (child, val) in adj[root]:
		if par == child:
			continue
		tot |= dfs(child, root, val)
	ans[root] = tot
	return tot
abe = 0

def traverse(root, par):
	global adj, ans, abe
	for (child, val) in adj[root]:
		if par == child:
			continue
		if ans[child] == 0:
			abe += 1
		else:
			traverse(child, root)

def hnbhai(tc):
	(n, m) = sd()
	m += 1
	abe = 0
	for i in range(30, -1, -1):
		if n >= m:
			break
		if n & 1 << i == m & 1 << i:
			continue
		if m & 1 << i:
			abe |= 1 << i
			n |= 1 << i
	print(abe)
for _ in range(sb()):
	hnbhai(_ + 1)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	for i in range(31)[::-1]:
		if n >= m:
			break
		if n >> i & 1 == m >> i & 1:
			continue
		if m >> i & 1:
			ans |= 1 << i
			n |= 1 << i
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	(a, b) = (m & ~n, ~m & n)
	c = a
	if b:
		z = 1
		while z <= b:
			c &= ~z
			z <<= 1
	else:
		x = m + 1 & ~m
		c = (c | x) & ~(x - 1)
	print(c)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	m += 1
	ans = 0
	b = 0
	while 1 << b + 1 <= max(n, m):
		b += 1
	for i in range(b, -1, -1):
		if n >> i & 1 and m >> i & 1 ^ 1:
			break
		elif n >> i & 1 ^ 1 and m >> i & 1:
			ans |= 1 << i
	print(ans)


import sys
input = sys.stdin.readline
LogN = 30

def main():
	(N, M) = map(int, input().split())
	M += 1
	Ans = 0
	for i in range(LogN - 1, -1, -1):
		if N >> i & 1:
			if 1 << i < M:
				M -= 1 << i
			else:
				break
		elif 1 << i < M:
			Ans += 1 << i
			M -= 1 << i
		elif 1 << i == M:
			Ans += 1 << i
			break
	print(Ans)
T = int(input())
for _ in range(T):
	main()


import sys
input = sys.stdin.buffer.readline

def solve():
	k = M + 1
	ans = 0
	for i in range(30, -1, -1):
		if N >> i & 1 > k >> i & 1:
			break
		ans |= N & 1 << i ^ k & 1 << i
	return ans
test_cases = int(input())
for test_case in range(test_cases):
	(N, M) = map(int, input().split())
	print(solve())


import sys
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def li():
	return [int(i) for i in input().split()]

def lli(rows):
	return [li() for _ in range(rows)]

def si():
	return input()

def ii():
	return int(input())

def ins():
	return input().split()

def solve():
	(n, m) = LI()
	if m < n:
		return 0
	elif n == m:
		if n % 2 == 0:
			return 1
		else:
			c = 0
			while n > 0:
				if n % 2 == 0:
					ans = c
					break
				n //= 2
				c += 1
			return 2 ** c
	else:
		nb = bin(n).lstrip('0b')
		mb = bin(m).lstrip('0b')
		nb = '0' * (len(mb) - len(nb)) + nb
		l = len(nb)
		sb = ''
		for i in range(l):
			if nb[i] <= mb[i]:
				sb += str(int(nb[i]) ^ int(mb[i]))
			else:
				sb += '0' * (l - i)
				return int(sb, 2)
		else:
			c = 0
			while m > 0:
				if n % 2 == 0 and m % 2 == 0:
					ans = sb[:l - c - 1] + '1' + '0' * c
					return int(ans, 2)
				n //= 2
				m //= 2
				c += 1
			else:
				return 2 ** c

def main():
	for _ in range(II()):
		sys.stdout.write(str(solve()) + '\n')
main()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mex = 0
	m += 1
	for i in range(30, -1, -1):
		if n >= m:
			break
		elif n >> i == m >> i:
			pass
		elif m >> i:
			mex |= 1 << i
			n |= 1 << i
	print(mex)


import sys
import io, os
import math
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
ceil = math.ceil
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def strinp(testcases):
	k = 5
	if testcases == -1 or testcases == 1:
		k = 1
	f = str(input())
	f = f[2:len(f) - k]
	return f

def print(x, end='\n'):
	sys.stdout.write(str(x) + end)

def ind(ch):
	return ord(ch) - ord('a')

def db(n):
	k = list(bin(n).replace('0b', ''))
	f = len(k)
	rem = 31 - f
	k = ['0'] * rem + k
	return k

def bd(arr):
	p = 1
	s = 0
	for i in range(len(arr) - 1, -1, -1):
		s += p * int(arr[i])
		p *= 2
	return s

def main():
	t = int(input())
	for _ in range(t):
		arr = list(map(int, input().split()))
		n = arr[0]
		m = arr[1]
		if n > m:
			print(0)
			continue
		bm = db(m)
		bn = db(n)
		ans = ['0'] * 31
		f = 30
		for i in range(31):
			if bm[i] == '1':
				f = i
				break
		g = -1
		xor = [0] * 31
		trig = False
		for i in range(31):
			if bm[i] == '1' and bn[i] == '0':
				ans[i] = '1'
			if bm[i] == '0' and bn[i] == '0':
				g = i
			xor[i] = int(bn[i]) ^ int(ans[i])
			if xor[i] > int(bm[i]):
				trig = True
				break
		if trig:
			c = bd(ans)
			print(c)
			continue
		ans[g] = '1'
		for i in range(g + 1, 31):
			ans[i] = '0'
		print(bd(ans))
main()


from collections import deque
import heapq
from math import sqrt
import operator
from operator import itemgetter
import sys
import copy
inf_var = 0
if inf_var == 1:
	inf = open('input.txt', 'r')
else:
	inf = sys.stdin
input = inf.readline

def read_one_int():
	return int(input().rstrip('\n'))

def read_one_float():
	return float(input().rstrip('\n'))

def read_list_of_ints():
	res = [int(val) for val in input().rstrip('\n').split(' ')]
	return res

def read_str():
	return input().rstrip()

def main():
	tests = read_one_int()
	for _ in range(tests):
		(n, m) = read_list_of_ints()
		if m < n:
			print(0)
			continue
		if m == 0:
			print(n ^ m + 1)
			continue
		n_bin = [0] * 30
		m_bin = [0] * 30
		bit = 1
		for i in range(30):
			if n & bit:
				n_bin[i] = 1
			elif bit <= n:
				n_bin[i] = 0
			if m & bit:
				m_bin[i] = 1
			elif bit <= m:
				m_bin[i] = 0
			bit <<= 1
		last_m_bit = None
		for i in range(len(m_bin) - 1, -1, -1):
			if m_bin[i] == 1:
				last_m_bit = i
				break
		bits_to_change = []
		can_decrease = False
		for i in range(last_m_bit - 1, -1, -1):
			if not can_decrease:
				if m_bin[i]:
					continue
				elif n_bin[i]:
					bits_to_change.append(i)
					can_decrease = True
			elif m_bin[i] ^ n_bin[i]:
				bits_to_change.append(i)
		if not bits_to_change:
			last_to_change = None
			for i in range(len(m_bin)):
				if not m_bin[i] and (not n_bin[i]):
					bits_to_change.append(i)
					last_to_change = i
					break
			for i in range(last_to_change - 1, -1, -1):
				if m_bin[i] ^ n_bin[i]:
					bits_to_change.append(i)
		for bit_n in bits_to_change:
			val = 1 << bit_n
			m ^= val
		res = m ^ n
		print(res)
main()


T = int(input())
for tc in range(T):
	(n, m) = map(int, input().split())
	p = m + 1
	sn = bin(n)[2:]
	sp = bin(p)[2:]
	sn = '0' * max(0, len(sp) - len(sn)) + sn
	sp = '0' * max(0, len(sn) - len(sp)) + sp
	res = []
	for i in range(len(sn)):
		if sn[i] == sp[i]:
			res.append('0')
		elif sn[i] == '0' and sp[i] == '1':
			res.append('1')
		elif sn[i] == '1' and sp[i] == '0':
			break
	zero_pad = '0' * (len(sn) - len(res))
	res.append(zero_pad)
	res = ''.join(res)
	print(int(res, 2))


def naiveSolve(n, m):
	v = set()
	for i in range(m + 1):
		v.add(n ^ i)
	for i in range(int(1000000000.0)):
		if i not in v:
			return i
	return
twoPowers = set()
x = 1
while x < 1000000000.0:
	twoPowers.add(x)
	x *= 2

def solve(n, m):
	if n > m:
		return 0
	if m + 1 in twoPowers:
		return m + 1
	ans = 0
	for i in range(29, -1, -1):
		if m & 1 << i > 0 and n & 1 << i == 0:
			ans += 1 << i
			if n ^ ans > m:
				return ans
	assert n ^ ans == m
	for i in range(31):
		if m & 1 << i == 0:
			ans = ans | 1 << i
			return ans
		ans = ans & ~(1 << i)
	pass

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m) = readIntArr()
		allans.append(solve(n, m))
	multiLineArrayPrint(allans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x):
	print('{}'.format(x))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 998244353
from math import gcd, floor, ceil
for _abc in range(1):
	main()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	s1 = []
	s2 = []
	for j in range(33):
		u = n >> j
		v = m >> j
		s1.append(u & 1)
		s2.append(v & 1)
	ans = 0
	for j in range(33):
		if s2[j] == 1:
			v = j
	for j in range(v + 1):
		ans = ans + 2 ** j
	for j in range(v, -1, -1):
		if s1[j] == 0 and ans - 2 ** j > m:
			ans = ans - 2 ** j
	if ans == m:
		ans = n + 2 ** (v + 1)
	if n <= m:
		print(ans ^ n)
	else:
		print(0)


from os import path
import sys, time
from math import ceil, floor, gcd, log, log2, factorial, sqrt
from collections import defaultdict, Counter, OrderedDict, deque
from itertools import combinations, accumulate
from bisect import *
from functools import reduce
from operator import mul
star = lambda x: print(' '.join(map(str, x)))
grid = lambda r: [lint() for i in range(r)]
INF = float('inf')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
import sys
from sys import stdin, stdout
from collections import *
from math import gcd, floor, ceil

def st():
	return list(stdin.readline().strip())

def inp():
	return int(stdin.readline())

def inlt():
	return list(map(int, stdin.readline().split()))

def invr():
	return map(int, stdin.readline().split())

def solve():
	(n, m) = invr()
	ans = float('inf')
	res = 0
	for i in range(31, -1, -1):
		if n & pow(2, i) and (not m & pow(2, i)):
			print(min(ans, res))
			return
		elif m & pow(2, i) and (not n & pow(2, i)):
			res += pow(2, i)
		elif not n & pow(2, i) and (not m & pow(2, i)):
			ans = min(ans, pow(2, i) + res)
	print(ans)
	return
t = 1
t = inp()
for _ in range(t):
	solve()


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	(a, b) = map(int, input().split())
	if a > b:
		print(0)
		continue
	b += 1
	aa = bb = 0
	R = a ^ b
	for j in range(31):
		bt = 1 << j
		aa += a & bt
		bb += b & bt
		if aa >= bb:
			R = min(a - aa ^ b - bb, R)
	print(R)


t = int(input())
for tt in range(t):
	(n, m) = map(int, input().split())
	m += 1
	z = 0
	for i in range(31)[::-1]:
		if n >> i & 1:
			m -= 1 << i
		elif m >= 1 << i:
			m -= 1 << i
			z += 1 << i
	print(z)


import sys
input = sys.stdin.readline
t = int(input())

def msb(x):
	res = 0
	while x > 0:
		x >>= 1
		res += 1
	return res

def solve(n, m):
	if n == 0:
		return m + 1
	if n > m:
		return 0
	n_msb = msb(n)
	m_msb = msb(m)
	if m_msb > n_msb:
		return (m >> n_msb << n_msb) + solve(n, m & (1 << n_msb) - 1)
	if m_msb == n_msb:
		if m == (1 << n_msb) - 1:
			return 1 << n_msb
		else:
			return solve(n - (1 << n_msb - 1), m - (1 << n_msb - 1))
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	print(solve(n, m))


def f(n):
	l = []
	while n > 0:
		l.append(n % 2)
		n //= 2
	return l

def solve(n, m):
	a = f(n)
	b = f(m)
	k = max(len(a), len(b))
	for _ in range(k - len(a)):
		a.append(0)
	for _ in range(k - len(b)):
		b.append(0)
	for j in range(k - 1, -1, -1):
		if a[j] == 1 and b[j] == 0:
			return (n ^ m) // 2 ** (j + 1) * 2 ** (j + 1)
	for j in range(k):
		if a[j] == 0 and b[j] == 0:
			return (n ^ m) // 2 ** (j + 1) * 2 ** (j + 1) + 2 ** j
	return 2 ** k
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	print(solve(n, m))


DEBUG = 0
if DEBUG == 1:
	data = open('sample1.in', 'r')

def readline():
	if DEBUG == 1:
		return data.readline().strip('\r\n')
	else:
		try:
			return input().strip('\r\n')
		except EOFError:
			return ''

def readi():
	return [int(t) for t in readline().split()]
(t,) = readi()
for id in range(t):
	(n, m) = readi()
	n = format(n, '032b')
	p = format(m + 1, '032b')
	k = [0] * 32
	for i in range(31, -1, -1):
		if n[i] == p[i]:
			k[i] = 0
		elif n[i] == '1' and p[i] == '0':
			for j in range(i, 32):
				k[j] = 0
		else:
			k[i] = 1
	kk = ''
	for i in range(32):
		kk += str(k[i])
	kk = int(kk, base=2)
	print(kk)
if DEBUG == 1:
	data.close()


def msb(x):
	i = 0
	p = 1
	assert x != 0
	while p < x:
		i += 1
		p = p << 1
	return i

def solve():
	(n, m) = map(int, input().split(' '))
	M = m + 1
	mex = 0
	for bit in range(29, -1, -1):
		l_bit = n >> bit & 1 > 0
		r_bit = M >> bit & 1 > 0
		set_this_bit = False
		if r_bit and (not l_bit):
			set_this_bit = True
		elif l_bit and (not r_bit):
			return mex
		if set_this_bit:
			mex = mex | 1 << bit
	return mex

def main():
	t = int(input())
	for tt in range(t):
		print(solve())
main()


from collections import defaultdict as dd
import math
import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))

def solve():
	(n, m) = mi()
	if n == 0 and m == 0:
		print(1)
		return
	if n > m:
		print(0)
		return
	exp = 40
	while 2 ** exp > m:
		exp -= 1
	val = 2 ** (exp + 1) - 1
	if m == val:
		print(m + 1)
		return
	while exp >= 0:
		temp = n
		if val - 2 ** exp > m and (temp >> exp) % 2 == 0:
			val -= 2 ** exp
		exp -= 1
	print(n ^ val)
q = nn()
for _ in range(q):
	solve()


import sys
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	m += 1
	ans = p = 0
	while m or n:
		(i, j) = (m & 1, n & 1)
		if i == 1 and j == 0:
			ans += 2 ** p
		elif i == 0 and j == 1:
			ans = 0
		p += 1
		m >>= 1
		n >>= 1
	return ans
for _ in range(int(input())):
	print(solve())


def solve():
	(n, m) = map(int, input().split())
	ans = 0
	flag = 0
	for i in range(30, -1, -1):
		(x, y) = (n >> i & 1, m >> i & 1)
		if flag == 0:
			if x == 1 and y == 0:
				flag = 1
			elif x == 0 and y == 1:
				ans |= 1 << i
	i = 0
	while flag == 0:
		if ans >> i & 1 == 0 and n ^ (ans | 1 << i) > m:
			ans |= 1 << i
			if i:
				ans = ans >> i << i
			flag = 1
		i += 1
	return ans
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	print(solve())


import math
import heapq
import string
from collections import deque
import sys
input = sys.stdin.readline
S = lambda : input()
I = lambda : int(S())
M = lambda : map(int, S().split())
L = lambda : list(M())
H = 1000000000 + 7
for _ in range(I()):
	(n, m) = M()
	m += 1
	bn = str(bin(n))[2:]
	bm = str(bin(m))[2:]
	if len(bn) < len(bm):
		bn = '0' * (len(bm) - len(bn)) + bn
	else:
		bm = '0' * (len(bn) - len(bm)) + bm
	s = ''
	for i in range(len(bm)):
		if bn[i] == '0' and bm[i] == '1':
			s += '1'
		elif bn[i] == '1' and bm[i] == '0':
			s += '0' * (len(bm) - i)
			break
		else:
			s += '0'
	print(int(s, 2))


def solve(n, m):
	if n > m:
		print(0)
		return
	result = 0
	m += 1
	a = bin(m)[2:]
	b = bin(n)[2:]
	if len(b) < len(a):
		b = '0' * (len(a) - len(b)) + b
	length = len(b)
	for x in range(length):
		if b[x] == '0' and a[x] == '1':
			result += 2 ** (length - x - 1)
		if b[x] == '1' and a[x] == '0':
			break
	print(result)
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	solve(n, m)


import time

def solve(n, m):
	if n == 0:
		return m + 1
	if m < n:
		return 0
	lm = len(bin(m)) - 3
	if lm > len(bin(n)) - 3:
		res = solve(n, m - (1 << lm))
		if len(bin(res)) - 3 == lm:
			return 1 << lm + 1
		else:
			return res + (1 << lm)
	res = solve(n - (1 << lm), m - (1 << lm))
	if len(bin(res)) - 3 == lm:
		return 1 << lm + 1
	else:
		return res
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	print(solve(n, m))


for _ in range(int(input())):
	(n, m) = map(int, input().split(' '))
	p = m + 1
	p = bin(p)[2:]
	z = bin(n)[2:]
	if len(z) >= len(p):
		p = p.zfill(len(z))
	else:
		z = z.zfill(len(p))
	k = ''
	for x in range(len(z)):
		if z[x] == '0' and p[x] == '0':
			k += '0'
		elif z[x] == '0' and p[x] == '1':
			k += '1'
		elif z[x] == '1' and p[x] == '0':
			for y in range(x, len(z)):
				k += '0'
			break
		else:
			k += '0'
	print(int(k, 2))


import sys
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	x = 0
	lastzz = 32
	for i in range(32, -1, -1):
		base = 1 << i
		if not n & base and (not m & base):
			lastzz = i
		elif n & base and (not m & base):
			print(x)
			return
		elif not n & base and m & base:
			x |= base
	x |= 1 << lastzz
	x &= ~((1 << lastzz) - 1)
	print(x)
tc = int(input().strip())
for _ in range(tc):
	solve()


from sys import *
ws = lambda : map(int, stdin.readline().strip().split())
li = lambda : list(map(int, stdin.readline().strip().split()))
mod = 1000000007

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def prod(l):
	ans = 1
	for i in range(len(l)):
		ans = ans * l[i]
	return ans

def sortindex(l, a):
	c = []
	if a == -1:
		rev = True
	else:
		rev = False
	for i in range(len(l)):
		c.append([l[i], i])
	x = sorted(c, reverse=rev)
	print(x)
	c = []
	for i in range(len(l)):
		c.append(x[i][1])
	return c
for _ in range(int(input())):
	(n, m) = ws()
	if n > m:
		print(0)
	else:
		t1 = bin(m + 1)
		t1 = t1[2:]
		t2 = bin(n)
		t2 = t2[2:]
		t8 = len(t1) - len(t2)
		t3 = '0' * t8
		t3 += t2
		t4 = t1[:t8]
		flag = 0
		for i in range(t8, len(t1)):
			if flag == 0:
				if t1[i] == '1':
					if t3[i] == '1':
						t4 += '0'
					else:
						t4 += '1'
				elif t3[i] == '1':
					t4 += '0'
					flag = 1
				else:
					t4 += '0'
			else:
				t4 += '0'
		print(int(t4, 2))


import sys
from os import path
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = 0
	m += 1
	for k in range(30, -1, -1):
		x = n & 1 << k
		y = m & 1 << k
		if x < y:
			ans = ans | 1 << k
		elif x > y:
			break
	print(ans)


def cal(n, m):
	mex = 0
	for i in range(31, -1, -1):
		if n >> i & 1 == m >> i & 1:
			continue
		if m >> i & 1:
			mex |= 1 << i
		else:
			break
	return mex
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	m += 1
	mex = 0
	if n <= m:
		mex = cal(n, m)
	print(mex)


def process(n, m):
	if n > m:
		return [0, 0]
	n1 = bin(n)[2:]
	m1 = bin(m)[2:]
	n1 = n1.zfill(len(m1))
	n1 = n1[::-1]
	m1 = m1[::-1]
	answer = 0
	is_good = None
	for i in range(len(m1)):
		if n1[i] == '1' and m1[i] == '0':
			is_good = i
	if is_good is None:
		first_zero = None
		for i in range(len(m1)):
			if m1[i] == '0':
				first_zero = i
				break
		if first_zero is None:
			return [2 ** len(m1), 0]
		answer = 2 ** first_zero
		for i in range(first_zero + 1, len(m1)):
			if m1[i] == '1' and n1[i] == '0':
				answer += 2 ** i
		return [answer, 0]
	for i in range(len(m1)):
		if i > is_good and n1[i] == '0' and (m1[i] == '1'):
			answer += 2 ** i
	return [answer, 1]
t = int(input())
for i in range(t):
	(n, m) = [int(x) for x in input().split()]
	print(process(n, m)[0])


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = bin(m + 1)[2:]
	b = bin(n)[2:]
	a1 = ['0'] * 30
	a2 = ['0'] * 30
	j = 29
	for i in range(len(a) - 1, -1, -1):
		a1[j] = a[i]
		j -= 1
	j = 29
	for i in range(len(b) - 1, -1, -1):
		a2[j] = b[i]
		j -= 1
	a3 = ['0'] * 30
	for i in range(30):
		if a1[i] == a2[i]:
			a3[i] = '0'
		elif a2[i] == '1' and a1[i] == '0':
			break
		else:
			a3[i] = '1'
	ans = int(''.join(a3), 2)
	print(ans)


def solve(n, m):
	ans = 0
	for i in range(31, -1, -1):
		nn = n | (1 << i) - 1
		nn ^= ans
		if nn <= m:
			ans += 1 << i
	return ans
for i in range(int(input())):
	(a, b) = map(int, input().split())
	print(solve(a, b))


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	if n > m:
		print(0)
	else:
		m += 1
		binLstOfm = list(map(int, bin(m)[2:]))
		binLstOfn = list(map(int, bin(n)[2:]))
		binLstOfn = [0] * (len(binLstOfm) - len(binLstOfn)) + binLstOfn
		s = ''
		for i in range(len(binLstOfm)):
			if binLstOfm[i] == 0 and binLstOfn[i] == 1:
				break
			if binLstOfm[i] == 1 and binLstOfn[i] == 0:
				s += '1'
			else:
				s += '0'
		while len(s) < len(binLstOfm):
			s += '0'
		print(int(s, 2))


from sys import stdin, gettrace
if gettrace():

	def inputi():
		return input()
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def msb(i):
	i |= i >> 1
	i |= i >> 2
	i |= i >> 4
	i |= i >> 8
	i |= i >> 16
	i += 1
	return i >> 1

def solve(n: int, m: int):
	m1 = m + 1
	bl = max(m1.bit_length(), n.bit_length())
	res = 0
	for i in range(bl - 1, -1, -1):
		bit = 1 << i
		if bit & n == 0 and bit & m1 != 0:
			res += bit
		elif bit & n != 0 and bit & m1 == 0:
			break
	return res

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		print(solve(n, m))
main()


t = int(input())

def solve():
	(n, m) = map(int, input().split())
	res = 0
	m += 1
	for i in range(31, -1, -1):
		mask = 1 << i
		if n & mask < m & mask:
			res += mask
		if n & mask > m & mask:
			break
	print(res)
for _ in range(t):
	solve()


def main():
	t = int(input())
	for _ in range(t):
		(n, m) = [int(word) for word in input().split()]
		if n > m:
			print(0)
		else:
			i = 0
			while 1 << i <= m:
				i += 1
			ans = 1 << i
			x = 0
			while i >= 0:
				y = x ^ 1 << i
				if n ^ y > m:
					ans = min(ans, y)
				elif n ^ x <= n ^ y:
					x = y
				else:
					pass
				i -= 1
			print(ans)
main()


def ind(ch):
	return ord(ch) - ord('a')

def db(n):
	k = list(bin(n).replace('0b', ''))
	f = len(k)
	rem = 31 - f
	k = ['0'] * rem + k
	return k

def bd(arr):
	p = 1
	s = 0
	for i in range(len(arr) - 1, -1, -1):
		s += p * int(arr[i])
		p *= 2
	return s

def main():
	t = int(input())
	for _ in range(t):
		arr = list(map(int, input().split()))
		n = arr[0]
		m = arr[1]
		if n > m:
			print(0)
			continue
		bm = db(m)
		bn = db(n)
		ans = ['0'] * 31
		f = 30
		for i in range(31):
			if bm[i] == '1':
				f = i
				break
		g = -1
		xor = [0] * 31
		trig = False
		for i in range(31):
			if bm[i] == '1' and bn[i] == '0':
				ans[i] = '1'
			if bm[i] == '0' and bn[i] == '0':
				g = i
			xor[i] = int(bn[i]) ^ int(ans[i])
			if xor[i] > int(bm[i]):
				trig = True
				break
		if trig:
			c = bd(ans)
			print(c)
			continue
		ans[g] = '1'
		for i in range(g + 1, 31):
			ans[i] = '0'
		print(bd(ans))
main()