InoryRWBY 2021-12-30 19:51 采纳率: 100%
浏览 26
已结题

不理解为什么超时了,复试上机题

问题如下:
描述
对于一个数n,如果是偶数,就把n砍掉一半;如果是奇数,把n变成 3*n+ 1后砍掉一半,直到该数变为1为止。 请计算需要经过几步才能将n变到1,具体可见样例。
输入描述:
测试包含多个用例,每个用例包含一个整数n,当n为0 时表示输入结束。(1<=n<=10000)
输出描述:
对于每组测试用例请输出一个数,表示需要经过的步数,每组输出占一行。

运行结果及报错内容

#include <iostream>
#include <cstdio>
using namespace std;
int main(){
    int n;
    cin>>n;
    while(n!=0){
        int m=0;
        while(n!=1){
            if(n%2==0)
                n=n/2;
            else
                n=(n*3+1)/2;
            m++;
        }
        cout<<m<<endl;
        cin>>n;
    }
    return 0;
}

出现了超时错误。

#include <iostream>
#include <cstdio>
using namespace std;
int main(){
    int n;
    while(cin>>n&&n!=0){
        int m=0;
        while(n!=1){
            if(n%2==0)
                n=n/2;
            else
                n=(n*3+1)/2;
            m++;
        }
        cout<<m<<endl;
    }
    return 0;
}

未超时
为什么前面一个会超时呀?

  • 写回答

1条回答 默认 最新

  • 书山客 2021-12-30 20:05
    关注
    
    #include <iostream>
    #include <cstdio>
    using namespace std;
    int main() {
        int n;
        if (!(cin >> n)) {
            cout << "输入错误" << endl;
            n = 0;
        }
        while (n != 0) {
            int m = 0;
            while (n != 1) {
                if (n % 2 == 0)
                    n = n / 2;
                else
                    n = (n * 3 + 1) / 2;
                m++;
            }
            cout << m << endl;
            if (!(cin >> n)) {
                cout << "输入错误" << endl;
                n = 0;
                continue;
            }
        }
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月7日
  • 已采纳回答 12月30日
  • 创建了问题 12月30日

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.