A. Make Even
Polycarp has an integer n that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times:
- Reverse the prefix of length l (in other words, l leftmost digits) of n. So, the leftmost digit is swapped with the l-th digit from the left, the second digit from the left swapped with (l−1)-th left, etc. For example, if n=123456789 and l=5, then the new value of nn will be 543216789.
Note that for different operations, the values of l can be different. The number l can be equal to the length of the number n — in this case, the whole number n is reversed.
Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.
Help Polycarp. Determine the minimum number of operations he needs to perform with the number n to make it even or determine that this is impossible.
You need to answer tt independent test cases.
The first line contains the number t (1≤t≤10^4) — the number of test cases.
Each of the following t lines contains one integer n (1≤n<10^9). It is guaranteed that the given number doesn't contain the digit 0.
Print t lines. On each line print one integer — the answer to the corresponding test case. If it is impossible to make an even number, print -1.
4
3876
387
4489
3
0
2
1
-1
In the first test case, n=3876n=3876, which is already an even number. Polycarp doesn't need to do anything, so the answer is 00.
In the second test case, n=387n=387. Polycarp needs to do 22 operations:
- Select l=2l=2 and reverse the prefix 38–––738_7. The number nn becomes 837837. This number is odd.
- Select l=3l=3 and reverse the prefix 837––––837_. The number nn becomes 738738. This number is even.
It can be shown that 22 is the minimum possible number of operations that Polycarp needs to do with his number to make it even.
In the third test case, n=4489n=4489. Polycarp can reverse the whole number (choose a prefix of length l=4l=4). It will become 98449844 and this is an even number.
In the fourth test case, n=3n=3. No matter how hard Polycarp tried, he would not be able to make an even number.
思路:这道题很容易理解,有数学规律,如果这个数本身就是一个偶数的话,就不需要做任何的处理。如果这个数是一个奇数,而首数字是一个偶数,那么就做一次处理即可。如果是一个奇数,而首位还是一个奇数的话,那就做两次处理就行了,第一次处理把偶数放在第一位,第二次处理就把偶数弄到最后,那么处理完后,整个数就是一个偶数!!
题解:
#include<iostream>
using namespace std;
int t;
int main(){
cin>>t;
for(int i = 0;i<t;i++){
int n,m,k=0;
cin>>n;
if(n%2==0){
cout<<"0"<<endl;
}else{
m=n;
while(m>=10){
m/=10;
if(m%2==0){
k++;
}
}
if(m%2==0){
cout<<"1"<<endl;
}else if(k>=1){
cout<<"2"<<endl;
}else{
cout<<"-1"<<endl;
}
}
}
return 0;
}

浙公网安备 33010602011771号