英文:
What's wrong with this code for the Palindrome Problem in LeetCode?
问题
以下是翻译的代码部分:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
num = str(x)
rev = ""
for i in num:
rev = i + rev
return rev
英文:
I am working on the Palindrome Number problem on LeetCode. The instructions are as followed:
"Given an integer x, return true if x is a palindrome, and false otherwise."
I used the following code to change the integer to a string and reverse the string.
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
num = str(x)
rev = ""
for i in num:
rev = i + rev
return rev
The input x = 121 is fine but x = -121 and x = 10 come back as true when they should come back as false. When I just use print with this code, I get 121- and 01, respectively. However, LeetCode says it's wrong. I'm confused as to why.
If someone could give me a little more insight into the error, I'd appreciate it. Thank you!
答案1
得分: 1
return rev == num
英文:
"Given an integer x, return true if x is a palindrome, and false otherwise."
you are just returning a reversed string.
change that to:
return rev == num
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论