#include<bits/stdc++.h>
using namespace std;
long long I[20], U[20];
long long cnt(long long x) {
if(x == 0) return 0;
long long maxx = 0, minx = 9;
while(x) {
maxx = max(maxx, x % 10ll);
minx = min(minx, x % 10ll);
x /= 10;
}
return maxx - minx;
}
int T, hst, a[20], b[20];
long long l, r, L[20], R[20];
int main() {
I[0] = 1;
for(int i = 1; i <= 18; i++)
I[i] = I[i - 1] * 10 + 1;
U[0] = 1;
for(int i = 1; i <= 18; i++)
U[i] = U[i - 1] * 10;
scanf("%d", &T);
while(T--) {
scanf("%lld %lld", &l, &r);
if(l == r) {
printf("%lld\n", l);
continue;
}
long long _l = l, _r = r;
for(int i = 0; i <= 18; i++) {
a[i] = _l % 10;
b[i] = _r % 10;
_l /= 10, _r /= 10;
}
L[0] = a[0], R[0] = b[0];
for(int i = 1; i <= 18; i++)
L[i] = L[i - 1] + U[i] * a[i], R[i] = R[i - 1] + U[i] * b[i];
//for(int i = 0; i <= 18; i++)
// printf("%lld %lld\n", L[i], R[i]);
hst = 18;
while(a[hst] == 0 && b[hst] == 0)
hst--;
if(a[hst] == 0) {
printf("%lld\n", 9 * I[hst - 1]);
continue;
}
int nlcp = hst;
while(a[nlcp] == b[nlcp]) nlcp--;
long long ans = l;
long long tmp;
tmp = L[18] - L[nlcp] + I[nlcp] * a[nlcp];
if(tmp >= l && cnt(tmp) < cnt(ans)) ans = tmp;
if(nlcp > 0) {
tmp = L[18] - L[nlcp - 1] + I[nlcp - 1] * a[nlcp - 1];
if(tmp >= l && cnt(tmp) < cnt(ans)) ans = tmp;
if(a[nlcp - 1] < 9) {
tmp = L[18] - L[nlcp - 1] + I[nlcp - 1] * (a[nlcp - 1] + 1);
if(cnt(tmp) < cnt(ans)) ans = tmp;
}
}
tmp = R[18] - R[nlcp] + I[nlcp] * b[nlcp];
if(tmp <= r && cnt(tmp) < cnt(ans)) ans = tmp;
if(nlcp > 0) {
tmp = R[18] - R[nlcp - 1] + I[nlcp - 1] * b[nlcp - 1];
if(tmp <= r && cnt(tmp) < cnt(ans)) ans = tmp;
if(b[nlcp - 1] > 0) {
tmp = R[18] - R[nlcp - 1] + I[nlcp - 1] * (b[nlcp - 1] - 1);
if(cnt(tmp) < cnt(ans)) ans = tmp;
}
}
for(int i = a[nlcp] + 1; i < b[nlcp]; i++) {
long long tmp = L[18] - L[nlcp] + I[nlcp] * i;
if(cnt(tmp) < cnt(ans)) ans = tmp;
}
printf("%lld\n", ans);
}
return 0;
}
1032A - Kitchen Utensils | 1501B - Napoleon Cake |
1584B - Coloring Rectangles | 1562B - Scenes From a Memory |
1521A - Nastia and Nearly Good Numbers | 208. Implement Trie |
1605B - Reverse Sort | 1607C - Minimum Extraction |
1604B - XOR Specia-LIS-t | 1606B - Update Files |
1598B - Groups | 1602B - Divine Array |
1594B - Special Numbers | 1614A - Divan and a Store |
2085. Count Common Words With One Occurrence | 2089. Find Target Indices After Sorting Array |
2090. K Radius Subarray Averages | 2091. Removing Minimum and Maximum From Array |
6. Zigzag Conversion | 1612B - Special Permutation |
1481. Least Number of Unique Integers after K Removals | 1035. Uncrossed Lines |
328. Odd Even Linked List | 1219. Path with Maximum Gold |
1268. Search Suggestions System | 841. Keys and Rooms |
152. Maximum Product Subarray | 337. House Robber III |
869. Reordered Power of 2 | 1593C - Save More Mice |