top1编程
← 返回题目
题解

【入门】是否是连续奇数

1 条题解

  • 0
    @ 2026-7-30 0:47:48

    解题思路

    按照题目要求直接计算。代码中使用简单的循环、判断和数组,把每一步写出来,方便理解。

    参考代码

    // 读取题目给出的数据。
    // 按照题意完成计算。
    // 输出最终答案。
    #include <iostream>
    using namespace std;
    int main() {
        int a[4];
        for (int i = 0; i < 4; i++) cin >> a[i];
        for (int i = 0; i < 4; i++) {
            for (int j = i + 1; j < 4; j++) {
                if (a[i] > a[j]) {
                    int t = a[i];
                    a[i] = a[j];
                    a[j] = t;
                }
            }
        }
        bool ok = a[0] % 2 == 1 && a[1] == a[0] + 2 && a[2] == a[1] + 2 && a[3] == a[2] + 2;
        if (ok) {
            cout << a[0] << "+2=" << a[1] << endl;
            cout << a[1] << "+2=" << a[2] << endl;
            cout << a[2] << "+2=" << a[3] << endl;
        } else {
            cout << a[3] << " " << a[2] << " " << a[1] << " " << a[0] << endl;
        }
        return 0;
    }
    

    复杂度

    代码只使用了题目需要的循环、判断和数组。若有 n 次循环,时间复杂度为 O(n);只使用固定数量变量时,空间复杂度为 O(1)。

    • 1