Description
你有一个整数n和s。一步中你可以使n增加1 (n =n+1)。找到最小步数使得n的每一位加起来小于或等于s。
lnput
第一行包含一个整数t (1<t<2.104)——测试数据组数。随后有t组测试数据每组测试数据包含两个整数n和s (1≤n ≤1015; 1<s ≤162)。
output
每组测试数据输出答案:将n变为每一位数字的和小于等于s的最小步数。
Sample lnput
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
OutPut
8
0
500
2128012501878
899999999999999999
Hint
对于第三组数据:n= 500+500=1000=>1+0+0+0<4
代码解答:
#include <iostream>
#include<vector>
#include <stdio.h>
#include <numeric>
#include<time.h>
#include<math.h>
using namespace std;
//生成随机长整数
vector<pair<long long, int>> RandomVector(int num)
{
vector<pair<long long, int>> res;
srand((unsigned)time(NULL));
for (int i = 0;i < num;i++)
{
pair<long long, int> temp;
temp.first = (long long)(rand() % 10000 + 1)*(long long)(rand() % 10000 + 1)*(long long)(rand() % 10000 + 1)*(long long)(rand() % 1000 + 1);//构建长整数
temp.second = rand() % 162 + 1;//构建限制数
res.push_back(temp);
}
return res;
}
vector<int> getNumVector(long long Num)
{
vector<int> NumVector;
while (Num > 0)
{
NumVector.push_back(Num % 10);
Num = Num / 10;
}
return NumVector;
}
long long GetLeastNum(long long LongInt, int LimitInt)
{
vector<int> NumVector = getNumVector(LongInt);
int SUM = accumulate(NumVector.begin(), NumVector.end(), 0);
if (SUM <= LimitInt)
return 0;
else
{
int index;
for ( index = NumVector.size() - 1;index >= 0; --index)
{
if (LimitInt > NumVector[index])
{
LimitInt -= NumVector[index];
}
else if (LimitInt == NumVector[index])
{
LimitInt -= NumVector[index];
break;
}
else
break;
}
long long powNum = (long long)pow(10, index+1);
return powNum- LongInt%powNum;
}
}
int main()
{
/*int t = 100;
auto NumVector = RandomVector(t);*/
int t;
long long LongInt;
int num;
vector<pair<long long, int>> NumVector;
cin >> t;
for (int i = 0;i < t;i++)
{
cin >> LongInt;
cin >> num;
NumVector.push_back(pair<long long, int>(LongInt, num));
}
vector<long long> res(NumVector.size());
for (size_t i = 0;i < NumVector.size();++i)
{
res[i] = GetLeastNum(NumVector[i].first, NumVector[i].second);
}
for (auto temp : res) cout << temp << endl;
return 0;
}
主要思路:
首先把长整数按照位数放置到vector之中。然后逆序由高到低求位数之和,如果大于限制数s,则通过遍历的方式,确定对应位数。