这段文本的中文翻译如下: 这段代码在LeetCode上用于回文问题有什么问题?

huangapple go评论91阅读模式
英文:

What's wrong with this code for the Palindrome Problem in LeetCode?

问题

以下是翻译的代码部分:

  1. class Solution(object):
  2. def isPalindrome(self, x):
  3. """
  4. :type x: int
  5. :rtype: bool
  6. """
  7. num = str(x)
  8. rev = ""
  9. for i in num:
  10. rev = i + rev
  11. 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):

  1. def isPalindrome(self, x):
  2. """
  3. :type x: int
  4. :rtype: bool
  5. """
  6. num = str(x)
  7. rev = ""
  8. for i in num:
  9. rev = i + rev
  10. 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

huangapple
  • 本文由 发表于 2023年3月3日 23:01:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定