codeforces B. Decrease the Sum of Digits - 模拟+优化

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值