codeforces B. Decrease the Sum of Digits
题干
You are given a positive integer n. In one move, you can increase n by one (i.e. make n:=n+1).
Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1≤t≤2⋅104) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1≤n≤1018; 1≤s≤162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
知识点&算法
模拟,对于位和超出要求的就在低位不断+1。
参考
题解
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,t,sum,ans,digitCarry;
//求数各位和的方法
ll getDigitSum(ll n){
ll res = 0;
while(n){
res += n % 10;
n /= 10;
}
return res;
}
int main()
{
cin>>n;
while(n--){
cin>>t>>sum;
if(getDigitSum(t) <= sum) cout<<0<<endl;
else{
ans = 0;
digitCarry = 1;
while(getDigitSum(t) > sum){
//如果一个数末尾为0,就/=10消去0,同时在digitCarry上累加10
//这样做相当于一个优化,对于10的整数倍不用再用1加,而是用10的倍数去加
if(t % 10 == 0){
t /= 10;
digitCarry *= 10;
}else{
t++;
ans += digitCarry;
}
}
cout<<ans<<endl;
}
}
return 0;
}