王廷瑋|數位醫療|智慧醫療: 9. Palindrome Number WFU

2024年7月2日 星期二

9. Palindrome Number

9. Palindrome Number


給定一個整數 x,如果 x 是回文數,則返回 true,否則返回 false。


Python


class Solution:
def isPalindrome(self, x: int) -> bool:
# Negative numbers are not palindromes
if x < 0:
return False
# Convert the integer to a string
s = str(x)
# Check if the string is the same forwards and backwards
return s == s[::-1]

16.44MB, 60ms


C++


class Solution {
public:
bool isPalindrome(int x) {
// Negative numbers are not palindromes
if (x < 0) {
return false;
}

// Store the original number
int original = x;
long reversed = 0;

// Reverse the integer
while (x != 0) {
int digit = x % 10;
reversed = reversed * 10 + digit;
x /= 10;
}

// Check if the reversed number is the same as the original
return original == reversed;
}
};

8.32MB, 0ms


Javascript


/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
// Negative numbers are not palindromes
if (x < 0) {
return false;
}

// Convert the integer to a string
let s = x.toString();

// Check if the string is the same forwards and backwards
let reversed = s.split('').reverse().join('');
return s === reversed;
};

58.63MB, 138ms