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

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

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

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:

确定