1 条题解

  • 0
    @ 2000-2-25 6:58:46

    【深基5.例2】小鱼的数字游戏

    解题思路

    读入非零数字并保存到数组,遇到 0 停止,再逆序输出数组。

    正确性说明

    数组保存了全部有效输入;从末尾到开头访问恰好得到逆序,终止标志不在数组中。

    易错点

    0 不输出;输入长度未知,用动态数组。

    复杂度

    数字个数 n,时间 O(n),空间 O(n)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        vector<int> a;
        int x;
        while (cin >> x && x != 0)
            a.push_back(x);
        for (int i = int(a.size()) - 1; i >= 0; i--) {
            if (i != int(a.size()) - 1)
                cout << " ";
            cout << a[i];
        }
        cout << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    79
    时间
    1000ms
    内存
    125MiB
    难度
    进阶
    标签
    递交数
    2
    已通过
    2
    上传者