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

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)


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))


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 = 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)


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))


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


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


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))


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
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)


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()


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())


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))


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()