回文函数的递归
有人帮我找出 isPalindrome(int) 函数有什么问题吗?
基本上这个函数检查一个数字是否是回文,我想完成 这是通过递归实现的。在函数内调用 isPalindrome(int) 时会出现一些问题。这让我很头疼。谢谢!
public boolean isPalindrome(int num) {
String s = Integer.toString(num);
if( s.length() == 1 ) {
return true;
}
if( s.length() == 2 && s.charAt(0) == s.charAt(1) ) {
return true;
}
if( s.length() > 2 ) {
if(s.charAt(0) == s.charAt(s.length()-1))
s = s.substring(1, s.length()-1);
**isPalindrome(Integer.parseInt(s));**
}
return false;
}
anyone helps me figure out what is wrong with my isPalindrome(int) function?
Basically this function checks if a number is a palindrome, and I wanted to accomplish
this by recursion. Some problem occurs when isPalindrome(int) is called within the function. This brought my a lot of headache. Thanks!
public boolean isPalindrome(int num) {
String s = Integer.toString(num);
if( s.length() == 1 ) {
return true;
}
if( s.length() == 2 && s.charAt(0) == s.charAt(1) ) {
return true;
}
if( s.length() > 2 ) {
if(s.charAt(0) == s.charAt(s.length()-1))
s = s.substring(1, s.length()-1);
**isPalindrome(Integer.parseInt(s));**
}
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在代码的这一部分中,
当第一个和最后一个字符不相等时,您没有给出 else 条件。
当它们不相等时,您应该返回 false。并且'return' isPalindrome(Integer.parseInt(s)),否则最后的return将在函数执行后执行。
In this part of your code
You have not given else for the condition when first and last characters are not equal.
You should return false when they are not equal. And also 'return' isPalindrome(Integer.parseInt(s)), else the last return will be executed after execution of the function.
你应该
返回 isPalindrome(Integer.parseInt(s));
而不仅仅是调用它。如果不这样做,当您从递归返回时,您将退出最后一个
if
的范围,并返回 false
,无论递归调用返回什么。you should
return isPalindrome(Integer.parseInt(s));
and not just invoke it.If you don't do it, when you come back from the recursion, you quit the last
if
's scope, andreturn false
, no matter what the recursive call returned.听起来像
[homework]
您可以通过在调试器中逐步执行代码来看到问题,但您遇到的一个问题是 isPalindrome 返回的值被忽略。您遇到的另一个问题是数字前半部分的
0
被忽略。这是因为您要将字符串转换为int
,然后再转换回 String,因此1020321
将显示为回文。顺便说一句:这个问题之前已经被问过很多次了。您是否将您的答案与网络上其他人的答案进行了比较?
Sounds like
[homework]
You would be able to see the problem by stepping through your code in a debugger, but one problem you have is that the value returned by isPalindrome is ignored.Another problem you have is that
0
in the first half of the number are ignored. This is because you are converting the string to anint
and back into a String so1020321
would appear to be a palindrome.BTW: This question has been asked many times before. Have you compared your answer with others on the web?
你想要s.Length()-2
,而不是s.Length()-1
你也可以改变你的第一个
true< /code> 测试
<= 1
,并删除length == 2
的特殊情况。You wants.Length()-2
, nots.Length()-1
Also you can change your first
true
test to<= 1
, and remove the special case oflength == 2
.