Topics
Find the count of really big numbers that are . A number is really big if the difference between and the sum of its digits (in decimal representation) is not less than .
Idea
The function is monotonic and non-decreasing. Thus, we can apply binary search boolean array framework to find the smallest (within ) that is really big. Note that if itself isn’t really big, then no number will be valid, otherwise, we know is the largest valid number. Finally, the count of valid numbers will be:
Time Complexity: where is the max number of digits (18 for the given problem, since ).
Space Complexity: .
Code
bool check(ll x, ll s) {
ll sod = 0;
ll og = x;
while (x) {
sod += x % 10;
x /= 10;
}
return og - sod >= s;
}
void solve() {
ll n, s;
cin >> n >> s;
ll lo = 0;
ll hi = n;
ll smallest = 0;
ll largest = n;
if (not check(largest, s)) {
cout << 0 << endl;
} else {
while (lo <= hi) {
ll mid = lo + (hi - lo) / 2;
if (check(mid, s)) {
smallest = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
cout << largest - smallest + 1 << endl;
}
}