洛谷 题号CF1409D Decrease the Sum of Digits
思路:数码的含义是各位之和(如213,2+1+3=6)。首先判断数码是否<=s,满足则直接输出0,否则因为如果不进位,那么数码肯定会越加越大,所以我们从右往左扫描这个数字(因为低位的位权小,进位代价低),然后把该位置为0(也就是说给n/10,因为是0,有无对数码无影响,如果该位为0,也不用管,因为只是提前加入答案,如90,变9,加1变10,再如80,变8,加1变9,下次变就只要1了,就是提前了),让下一位+1,然后把进位的代价加到结果里(即该位的位权*进位需要的数字),再把n/10,继续判断判断数码是否<=s,不行继续做。
代码
#include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
ull t,n,s,total,ans,i;
ull shuma(ull x){
ull sum=0;
while(x){
sum+=x%10;
x/=10;
}
return sum;
}
int main(){
scanf("%llu",&t);
while(t--){
ans=0;
scanf("%llu%llu",&n,&s);
total=shuma(n);
if(total<=s){
printf("0\n");
continue;
}
for(i=1;shuma(n)>s;i*=10){
ans+=(10-n%10)*i;
n/=10;
n++;
}
printf("%llu\n",ans);
}
}