leetcode.com-problemset-all-009 - Palindrome Number

- 3 mins

题目描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

难易程度

Example:

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.

PHP实现

方法一

//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;
    }
}

Go实现

方法一

//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

}

PS

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora