c++ - 在序列中找到最小奇数和最大偶数

标签 c++

我正在尝试这个非常简单的问题:

输入:

包含一个整数 n (n ≤ 10^6) - 序列中元素的数量,在它之后 ai (1<=i<=n) - 序列中的元素

输出:

写出数列的最小奇数和最大偶数。如果没有这样的数字,那么写“-1”而不是这个数字。

输入格式:

5

1 2 3 4 5

输出:1 4

我试的是这个,但是还是过不了在线判断。

#include <iostream>
//#include <cmath>

using namespace std;
int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int n, a, min, max;
    cin >> n;
    min = INT16_MAX; max = 0;
    for (int i = 0; i < n; i++)
    {
        cin >> a;
        if (a >= max && a % 2 == 0) { max = a; }
        if (a <= min && a % 2 != 0) { min = a; }
    }

    if (min == INT16_MAX && min != 1) { min = -1; }
    if (max == 0) { max = -1; }
    cout << min << " " << max;
    return 0;
}

为了更好地理解需要什么,如果输入:

5

2 4 2 5 4

输出应该是:-1 4 还是 5 4?

最佳答案

发布的代码,找到最大的偶数,遵循这个步骤

int max = 0;
// ...
{
    // ...
    if (a >= max && a % 2 == 0) { max = a; }
}

if (max == 0) { max = -1; }

不过,引用的问题似乎没有指定输入值的范围。因此,对于每个小于零的偶数值,这都会给出错误的结果。

用于查找最小值的逻辑中存在类似的问题,该逻辑假定所有奇数值都小于或等于 INT16_MIN


if the input (...) 2 4 2 5 4 the output should be: -1 4 or 5 4?

根据我对引用问题的理解,输出应该是 5 4。 如果数字是,例如,它将是 -1 4 2 4 2 6 4(没有奇数)。


为确保找到的极值有效,您可以使用几个标记值,即不可能是(最小)奇数和不可能是(最大)偶数的值:

const int odd_sentinel = 0;     // It isn't odd...
const int even_sentinel = -1;   // It's not even
int min_odd = odd_sentinel;
int max_even = even_sentinel;

int x;
while ( std::cin >> x )
{
    if ( x % 2 )
    {
        if ( min_odd == odd_sentinel  ||  x < min_odd )
            min_odd = x;
    }
    else
    {
        if ( max_even == even_sentinel  ||  x > max_even )
            max_even = x;
    }
}

std::cout << (min_odd == odd_sentinel ? -1 : min_odd) << ' '
          << (max_even == even_sentinel ? -1 : max_even) << '\n';

关于c++ - 在序列中找到最小奇数和最大偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154045/

相关文章:

c++ - 为什么对于gcc 'UNIX'和 'unix'宏不是同一回事?

c++ - linux pthread - 有没有办法不将所有成员创建为静态成员?

c++ - Foo *p = 0;p->p() 如何有效?

c++ - 在编译时检查销毁顺序约束

c++ - opencv 删除视频提要到帧

c++ - Qt - 控制外部进程

c++ - 对象的大小与没有指针的类的大小不同

c++ - 关于const或friendship的使用

c++ - 为什么 std::isnan 不是 constexpr?

c++ - 如何在 Linux 下为 C/C++ 中的计时器设置亲和性?