D - Decrease the Sum of Digits
只要发现进位可以直接抹掉后面的位数就行了,剩下的就是在第几位进位的问题。写得繁琐了一点。
int main()
{
//ios::sync_with_stdio(false);
//while (scanf("%d%d",&n,&m)!=EOF){
int t; cin >> t; while (t--) {
LL n; int s;
cin >> n >> s;
string str = to_string(n);
int len = str.length();
int cnt = 0;
for (int i = 0; i < len; i++) {
cnt += str[i] - '0';
}
if (cnt <= s) {
cout << 0 << endl;
continue;
}
cnt = 0;
//第一位数>=s,必须进位
if (str[0] - '0' >= s) {
//从后往前找到第一个需要借位做减法的位置
int mark = -1;
for (int k = len - 1; k > 0; k--) {
if (str[k] - '0' != 0) {
mark = k;
break;
}
}
//不需要借位做减法
if (mark == -1) {
cout << 10 - (str[0] - '0');
for (int k = 1; k < len; k++) cout << 0;
cout << endl;
continue;
}
else {
//记录当前位是否会减出前导零
int first = 1;
for (int k = 0; k < len; k++) {
if (k < mark) {
//9-str[k]会减出前导零,跳过
if (first && str[k] == '9') continue;
else {
cout << 9 - (str[k] - '0');
first = 0;
}
}
else if (k == mark) cout << 10 - (str[k] - '0');
else if (k > mark) cout << 0;
}
cout << endl;
continue;
}
}
else {
for (int i = 0; i < len; i++) {
cnt += str[i] - '0';
//累加到第i位之后超出s,在第i位往前进一位
//如235 5,加到第1位(从0起计)后=5,则应进位成300,答案即300-235
if (cnt >= s) {
int mark = -1;
for (int k = len - 1; k > i; k--) {
if (str[k] != '0') {
mark = k;
break;
}
}
if (mark == -1) {
cout << 10 - (str[i] - '0');
for (int k = i + 1; k < len; k++) cout << 0;
cout << endl;
break;
}
else {
int first = 1;
for (int k = i; k < len; k++) {
if (k < mark) {
if (first && str[k] == '9') continue;
else {
cout << 9 - (str[k] - '0');
first = 0;
}
}
else if (k == mark) cout << 10 - (str[k] - '0');
else if (k > mark) cout << 0;
}
cout << endl;
break;
}
}
}
}
}
return 0;
}