[LeetCode]Palindrome Number

Palindrome Number

給一整數 x ,如果反轉該數字一樣的話,則回傳 true。

Example 1

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2

Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.


解法

Palindrome 回文,也就是正讀反讀都能讀通,比如 12321 從前面看或後面看都是一樣的數字,但 -123321 的回文是 12321- ,所以負整數無法符合回文的條件。

將原始整數利用除以 10 取出餘數,加總該餘數及位數,直到原始整數不能再除為止。

class Solution {

    /**
     * @param Integer $x
     * @return Boolean
     */
    function isPalindrome($x) {
        $temp_x = $x;
        $new_x = 0;

        while ($temp_x != null) {
            $d = $temp_x % 10;
            $new_x = $new_x * 10 + $d;
            $temp_x = intval($temp_x / 10);
        }

        if ($new_x == $x && $new_x >= 0)
            return true;
        else
            return false;
    }
}

另一個解法是將數值轉成字串,用 PHP 的內建函式 strrev

// 反轉字串
if ($x == strrev($x))
    return true;
else
    return false;


留言