9. Palindrome Number
Description
YDetermine 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.
Follow up:
Coud you solve it without converting the integer to a string?
分析和方案
回文判断:字符串倒序排列之后是否和原字符串相同.
回文亦称回环,是正读反读都能读通的句子,亦有将文字排列成圆圈者,是一种修辞方式和文字游戏。回环运用得当,可以表现两种事物或现象相互依靠或排斥的关系。
例:
喜欢的少年是你,你是年少的欢喜
Madam, I'm Adam.
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
return String(x).split('').reverse().join('') === String(x);
};
对javascript来说,字符倒叙之后判断一下是否相同是很容易的。不过这个解法效率并非最好
最快
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
let num = x;
let reversedNum = 0;
while(num > 0) {
let remainder = num % 10;
num = (num - remainder) / 10;
reversedNum = reversedNum * 10 + remainder;
if (reversedNum === x) return true;
}
return x === 0;
};
从数字最低位按位取值,每次先*10再加取到的值,实际上做到了把数字倒序排列成新数值。最后判断是否和原值相同。
第二
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
if (x < 0) return false;
if ((x / 10) >> 0 === 0) return true;
if (x % 10 === 0) return false;
let revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10
x = (x / 10) >> 0
}
return x === revertedNumber || x === (revertedNumber / 10) >> 0;
};
可能是入口if判断比较多,拖慢了速度,核心思路和最快类似
第三
var isPalindrome = function(x) {
if(x<0){
return false
}else if(x>=0 && x<9){
return true
}
var d = []
num = x
while(num>0){
d.push(num%10)
num = ~~(num/10)
}
var i = 0, j = d.length - 1
while(i < j){
if(d[i] == d[j]){
j--
i++
} else {
return false
}
}
return true
}
对数据做了预判