我可以获得有关 C 语言中的“isPalindrome()”函数的一些反馈吗?
我正在用 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,虽然我可以知道我的代码何时编译并且不需要花一整天的时间来解决问题,但我没有任何专家的眼睛来告诉我是否“我走在正确的轨道上。
那么,对我的代码有什么改进或建议吗?
非常感谢!
I'm writing some useful functions in C. One of them is isPalindrome()
.
I figured to determine if a number is a palindrome or not, I should...
- get all digits in an array
- iterate through with two indexes - start one at 0 and one to the array count
- increment/decrement the indexes whilst subscripting the array whilst they match and if the array count gets to 0 we have a palindrome (i.e. finishing going through all digits).
I came up with...
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;
}
Is this generally how it is done?
I'm learning C by myself, and although I can tell when my code compiles and doesn't take all day to work something out, I don't have any expert eyes to tell me if I'm on the right track.
So, any improvements or suggestions on my code?
Thanks very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你只需要循环 while
i > j。一旦
i <= j
,您只需再次检查所有字符。You only have to loop while
i > j
. Oncei <= j
, you are just checking all the characters a second time.尽管在下面使用内联
++
和--
运算符可能看起来很聪明:如果将这些放在中,您的代码将更容易阅读循环体:
这样,代码的读者就不必考虑在条件测试中更改
i
和j
的值可能产生的副作用。对编译代码的速度可能不会产生可测量的影响(尽管,如果性能对此函数很重要,您应该与编译器检查)。此外,您还遇到了一个错误,如果
i == 0
,您将访问places[-1]
。Although using inline
++
and--
operators in the following might seem clever:your code will be easier to read if you put those inside the loop body:
This way, the reader of the code won't have to think about the possible side effects of changing the values of
i
andj
within the conditional test. There will probably be no measurable effect on the speed of the compiled code (although, if performance is important to this function, you should check with your compiler).Also, you've got a bug where you will access
places[-1]
ifi == 0
.我只是使用 sprintf 来“将字符串转换为数字”:
I'd just use
sprintf
to "convert the string to digits":在java中
在c++和c中
注意,如果您需要对数字输入执行此操作,则需要编写itoa函数。或者使用(链接)。
一般都是这样做的。这也适用于所有基地,而不仅仅是 10 个。
In java
In c++ and c
Note, You need to write itoa function, if you need to do this for a number input. Or use ( link ).
Thats how it is generally done. This would also work for all bases and not only 10.