美文网首页
算法:一道简单的改错题

算法:一道简单的改错题

作者: yehkong | 来源:发表于2018-09-19 15:19 被阅读0次

    在算法竞赛书中有这样一道思考题:

    ///统计字符串中数字1的个数
    #include <stdio.h>
    #include <string.h>
    
    #define maxn 10000000 + 10
    
    int main(int argc, const char * argv[]) {
        char s[maxn];
        scanf("%s",s);
        int tot = 0;
        for (int i = 0; i < strlen(s); i++)
            if (s[i] == 1) tot++;
            printf("%d\n",tot);
        return 0;
    }
    

    该程序至少有3个问题,其中一个导致程序无法运行,另一个导致结果不正确,还有一个导致销量低下。

    在xcode中把这个段代码码上,编译可以通过,运行出错。

    这三个问题我想是这样的:


    1.png

    问题1. 数组的维数太大,这个是跟操作系统的堆栈有关吧,不同的平台不同。往上改到的最大值我没去尝试,这里改到100.
    问题2. 循环判断中每次都要调用strlen(s),这个可以提到循环起前面去计算,提高效率
    问题3. 字符'1'的ascii不是数字1而是49,所以应该把区别字符'1'和数字1.

    改后的代码:

    #define maxn 100 + 10
    
    int main(int argc, const char * argv[]) {
        char s[maxn];
        scanf("%s",s);
        int tot = 0;
        unsigned long len = strlen(s);
        for (int i = 0; i < len; i++)
            if (s[i] == '1') tot++;
            printf("%d\n",tot);
        return 0;
    }
    

    另外的写法:

    int main(int argc, const char * argv[]) {
        int tot = 0;
        char ch;
        while((ch = getchar()) != '\n')
            if(ch == '1') ++tot;
        printf("%d\n", tot);
    }
    

    相关文章

      网友评论

          本文标题:算法:一道简单的改错题

          本文链接:https://www.haomeiwen.com/subject/hgixnftx.html