2

我正在用 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

4 回答 4

5

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

于 2010-10-29T01:13:28.657 回答
2

尽管在下面使用内联++--运算符可能看起来很聪明:

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

如果将代码放在循环体中,您的代码将更易于阅读:

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

这样,代码的读者就不必考虑更改条件测试的值ij在条件测试中可能产生的副作用。对编译代码的速度可能没有可测量的影响(尽管,如果性能对这个函数很重要,你应该检查你的编译器)。

此外,您还有一个错误,您可以在其中访问places[-1]if i == 0

于 2010-10-29T01:22:22.950 回答
1

我只是sprintf用来“将字符串转换为数字”:

char places[100];
sprintf(places, "%i", num);
i = strlen(places);
于 2010-10-29T02:00:07.657 回答
1

在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);
}

注意,如果您需要为数字输入执行此操作,您需要编写itoa函数。或使用(链接)。

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

于 2010-10-29T02:21:11.297 回答