代码之家  ›  专栏  ›  技术社区  ›  alex

我能在C语言中得到一些关于这个'isparandrome()'函数的反馈吗?

  •  2
  • alex  · 技术社区  · 14 年前

    我在用C语言写一些有用的函数,其中之一是 isPalindrome()

    我想确定一个数字是不是回文,我应该。。。

    • 使用两个索引遍历-从0开始一个索引到数组计数
    • 当索引匹配时,在订阅数组时递增/递减索引,如果数组计数为0,则有一个回文(即完成所有数字的遍历)。

    我想到了。。。

    int isPalindrome(int num) {
    
        int places[100];
        int i = 0;
        while (num > 0) {
            places[i++] = num % 10; 
            num /= 10;
        }
    
        int j = 0;
        while (i >= 0 && places[j++] == places[--i]) {
        }
        return i == -1;
    
    }
    

    一般都是这样做的吗?

    我自己在学习C语言,虽然我知道我的代码什么时候编译,不需要花一整天的时间就可以完成,但我没有 告诉我我是不是在正确的轨道上。

    那么,对我的代码有什么改进或建议吗?

    4 回复  |  直到 14 年前
        1
  •  5
  •   James McNellis    14 年前

    你只需要在 i > j . 一次 i <= j ,您只是在第二次检查所有字符。

        2
  •  2
  •   Greg Hewgill    14 年前

    ++ -- 下面的运算符可能看起来很聪明:

    while (i >= 0 && places[j++] == places[--i]) { 
    } 
    

    里面

    while (i >= 0 && places[j] == places[i-1]) { 
        j++;
        i--;
    } 
    

    这样,代码的读者就不必考虑更改 i j 在条件测试中。可能不会对编译代码的速度产生可测量的影响(不过,如果性能对该函数很重要,则应与编译器一起检查)。

    而且,你有一个漏洞可以访问 places[-1] i == 0 .

        3
  •  1
  •   sth    14 年前

    我就用 sprintf

    char places[100];
    sprintf(places, "%i", num);
    i = strlen(places);
    
        4
  •  1
  •   Margus    14 年前

    在java中

    static boolean isPalindrome(String p) {
        return p.equals(new StringBuilder(p).reverse().toString());
    }
    

    在c++和c中

    int IsPalindrome(char *string) {
        int bottom = 0, top;
    
        top = strlen(string) - 1;
        while(bottom < top && string[bottom] == string[top]) {
            ++bottom;
            --top;
        }
        return (bottom >= top ? 1:0);
    }
    

    注意,你需要写 函数,如果需要对数字输入执行此操作。或使用( link

    一般都是这样做的。这也适用于所有基地,而不仅仅是10个。