立扣題:給你一個整數(shù) x ,如果 x 是一個回文整數(shù),返回 true 笛丙;否則屎勘,返回 false 。
分析:回文數(shù)就是我們將一個數(shù)字無論是正著讀還是反著讀,結(jié)果都是相同的數(shù),所以我們可以進行數(shù)字反轉(zhuǎn),然后對比捎琐,得結(jié)果。
☆代碼
let x = -121;
function isPalindrome(x){
let temp = x; //存一個做對比
//先轉(zhuǎn)成字符串裹匙,轉(zhuǎn)成數(shù)組瑞凑,在反轉(zhuǎn),在轉(zhuǎn)成字符串
let flag = String(x).split('').reverse().join('')
if (temp == flag) {
return true
}else{
return false
}
}
console.log(isPalindrome(x));
☆進階代碼
let x = -121;
function isPalindrome(x){
if(x<0)return false //判斷是否是負(fù)數(shù)概页,是直接返回false
let temp = x;
let res = 0
while(x != 0){ //循環(huán)從個位取數(shù)然后相加
let cur = x % 10;
x = Math.floor(x / 10);
res = res * 10 + cur;
}
return temp == res ? true : false;
}
console.log(isPalindrome(x));
有更好的方法歡迎留言籽御!