Given an integer x, return true if x is a palindrome, and false otherwise.
給予一個整數 x,如果 x 是一個回文的話,回傳 true,否則回傳 false。
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.
Solution:
1. 回傳 x 的判斷式:
a = x 的反轉後字串。
b = x.的初始字串。
return a === b
ex. 0 只有一位數字,正向和反向讀都是 0。
Code 1:
var isPalindrome = function(x: number): boolean {
if (x < 0) return false;
if (x === 0) return true;
return x.toString().split("").reverse().join("") === x.toString();
};
FlowChart:
Example 1
Input: x = 121
console.log(x.toString().split('').reverse().join(''), x.toString())
return 121 === 121 //true
Example 2
Input: x = -121
console.log(x.toString().split('').reverse().join(''), x.toString())
return 121- === -121 //false
Example 3
Input: x = 10
console.log(x.toString().split('').reverse().join(''), x.toString())
return 10 === 01 //false
reverse():
var a = ['one', 'two', 'three']; var reversed = a.reverse(); console.log(a); // ['three', 'two', 'one'] console.log(reversed); // ['three', 'two', 'one']
Code 2:
var isPalindrome = function(x: number): boolean {
if (x < 0) return false;
if (x === 0) return true;
let num: number = x,
reverseNum: number = 0;
while (num > 0) {
reverseNum = reverseNum * 10 + (num % 10);
num = Math.floor(num / 10);
}
return reverseNum === x;
};
Code 3:
var isPalindrome = function (x: number): boolean {
if (x < 0) return false;
if (x === 0) return true;
return `${x}`.split("").reverse().join("") === `${x}`.toString();
};