题目链接:点击打开链接
大意:
给定一个十进制下最多10
5位的数字,请你求出和这个数字的差的绝对值最小的二数,若答案不唯一,输出最小的那个。
也就是说,给定数字n,求出m,使得abs(n-m)最小且m[i] mod 2 = 0
思路:思路很好想,主要是细节,直接上代码吧。
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<string>
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<map>
#define FAST ios::sync_with_stdio(false)
typedef long long ll;
const int maxn = 1000005;
using namespace std;
char a[maxn];
int b[maxn];
int main()
{
FAST;
int t;
cin >> t;
while(t--){
cin >> a;
int len = strlen(a);
for(int i = 0; i < len; i++){
b[i] = a[i] - '0';
}
if(len == 1){
b[0] & 1 ? cout << b[0] - 1 << endl : cout << b[0] << endl;
}
else{
int pos = len, x;
for(int i = 0; i < len; i++){
if(b[i] & 1){
pos = i;
x = b[i];
break;
}
}
if(x == 9){
for(int i = pos; i < len; i++){
b[i] = 8;
}
}
else{
bool flag = false;
for(int i = pos + 1; i < len; i++){
if(b[i] > 4) { flag = true; break;}
if(b[i] < 4) break;
//if(b[i] == 4) continue;
}
if(flag){
b[pos]++;
for(int i = pos + 1; i < len; i++){
b[i] = 0;
}
}
else{
b[pos]--;
for(int i = pos + 1; i < len; i++){
b[i] = 8;
}
}
}
int pos2;
for(int i = 0; i < len; i++){
if(b[i]){
pos2 = i;
break;
}
}
for(int i = pos2; i < len; i++){
cout << b[i];
}
cout << endl;
}
}
return 0;
}
over