Given a natural number x You can perform the following operationchoose a positive integer k and round x to the k-th digitNote that the positions are numbered from right to left starting from zero If t
Here is a possible C++ solution for the problem:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
string x;
cin >> x;
int n = x.length();
int k = 0;
for(int i = n-1; i >= 0; i--) {
if(x[i] >= '5') {
k = i;
break;
}
}
for(int i = k; i < n; i++) {
if(x[i] == '9') {
x[i] = '0';
if(i == n-1) {
x = '1' + x;
n++;
}
} else {
x[i]++;
}
}
for(int i = 0; i < k; i++) {
x[i] = '0';
}
cout << x << endl;
}
return 0;
}
This solution iterates through each test case, and for each test case, it finds the rightmost position k where the digit is greater than or equal to 5. Then, it increases the digit at position k by 1 and replaces all digits before position k with zeros. If the digit at position k is 9, it replaces it with 0 and searches for the next position k' where the digit is less than 9 to increase it by 1. Finally, it outputs the resulting number
原文地址: https://www.cveoy.top/t/topic/iwSK 著作权归作者所有。请勿转载和采集!