Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
//88ms
class Solution {
/**
* @param Integer $x
* @return Boolean
*/
function isPalindrome($x) {
return strrev($x) == $x;
}
}
//80ms
class Solution {
/**
* @param Integer $x
* @return Boolean
*/
function isPalindrome($x) {
if ($x < 0) return false;
$res = 0;
$s = $x;
while ($s > 0) {
$res = $res*10 + $s%10;
$s = floor($s/10);
}
if ($res == $x) return true;
return false;
}
}
//56ms
func isPalindrome(x int) bool {
if x < 0 {
return false
}
s, res := x, 0
for s > 0 {
res = res*10 + s%10
s = s/10
}
return res == x;
}
//56ms
func isPalindrome(x int) bool {
if x < 0 || (x != 0 && x%10 == 0) {
return false
}
rev := 0
for ; x > rev; x = x / 10 {
rev = rev*10 + x%10
}
return x == rev || x == rev/10
}
//40ms
func isPalindrome(x int) bool {
if x < 0 || (x%10 == 0 && x != 0) {
return false
}
var revertedNum int
for x > revertedNum {
last := x % 10
x /= 10
revertedNum = revertedNum*10 + last
}
return x == revertedNum || x == revertedNum/10
}
方法一
一般是自己实现的方法,其他方式
是在discuss
中查找的更为优秀的方法,用作学习和借鉴。