回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
解题思路
- 如果数字小于0,那次数肯定不为回文数
- 如果数字大于0,小于10,肯定为回文数
- 对比首位与末尾数字是否相同,如果相同,则摘除第一位与最后一位,继续比较,直至数字剩余一位或者没有
- 如果不同,则此数部位回文数
代码如下
var isPalindrome = function (x) {
if (x < 0) return false;
if (x < 10) return true;
//取出x最多为10的n次方
let n = 10 ** Math.floor(Math.log10(x));
while (n > 1 && x > 0) {
if (Math.floor(x / n) !== x % 10) return false;
x = Math.floor((x % n) / 10);
n /= 100;
}
return true;
};