练习codeforces 1611A. Make Even

题目如下
A. Make Even
time limit per test1 second
memory limit per test256 megabytes
Polycarp has an integer 𝑛 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 𝑙 (in other words, 𝑙 leftmost digits) of 𝑛. So, the leftmost digit is swapped with the 𝑙-th digit from the left, the second digit from the left swapped with (𝑙−1)-th left, etc. For example, if 𝑛=123456789 and 𝑙=5, then the new value of 𝑛 will be 543216789.
Note that for different operations, the values of 𝑙 can be different. The number 𝑙 can be equal to the length of the number 𝑛 — in this case, the whole number 𝑛 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 𝑛 to make it even or determine that this is impossible.

You need to answer 𝑡 independent test cases.

Input
The first line contains the number 𝑡 (1≤𝑡≤104) — the number of test cases.

Each of the following 𝑡 lines contains one integer 𝑛 (1≤𝑛<109). It is guaranteed that the given number doesn't contain the digit 0.

Output
Print 𝑡 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.
题目大意
对于每个样例,确认是否通过“翻转”操作来获得一个偶数,如果可以,输出操作次数;否则,输出-1;
操作如下,对于每个数可以进行n次操作,你可以对给定的数的前l长度的数字进行整体的翻转,例如3457,你想翻转前3个,那么就得到5437;

题目分析
若给定的数是偶数,那么直接得出0次;
只有当给定的数中存在偶数时,才有可能通过翻转操作得到一个偶数,我们只要找到任意偶数所在的位置,通过翻转使得偶数作为首位,那么再翻转一次即可得到偶数;
同时,若首位即位偶数,那么只需翻转一次;
所以,核心在于判断偶数的位置

如下

点击查看代码
#include <stdio.h>
#include <string.h>

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        char s[20];
        scanf("%s", s);
        int len = strlen(s);
        if((s[len - 1] - '0') % 2 == 0){
            printf("0\n");
            continue;
        }
        if((s[0] - '0') % 2 == 0){
            printf("1\n");
            continue;
        }
        int found = 0;
        for(int i = 1; i < len - 1; i++){
            if((s[i] - '0') % 2 == 0){
                found = 1;
                break;
            }
        }
        if(found)
            printf("2\n");
        else
            printf("-1\n");
    }
    return 0;
}
posted @ 2025-07-04 21:30  sirro1uta  阅读(23)  评论(0)    收藏  举报