🙌

LeetCode #9 Palindrome Number

2024/09/12に公開

問題概要

入力値:x (int)
出力値:bool
問題のリンク

入力例

x: 131
answer: true

解答例1

Convert to string
計算量:n

Python

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 or (x > 0 and x%10 == 0):
            return False
        string_val = str(x)
        return string_val == string_val[::-1]

Runtime: 53ms
Beats: 17.09%

解答例2

Not convert to string
計算量:n

Python

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 or (x > 0 and x % 10 == 0):
            return False
        result = 0
        while x > result:
            result = result * 10 + x % 10
            x = x // 10
            
        return True if (x == result or x == result // 10) else False

Runtime: 40ms
Beats: 58.10%

C++

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) {
            return false;
        }

        int result = 0;
        while (x > result) {
            result = result * 10 + x % 10;
            x /= 10;
        }
        return (x == result || (x == result / 10));
    }
};

Runtime: 4ms
Beats: 84.84%

Discussion