给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
java:
import java.util.*;
public class Solution {
/**
*
* @param x int整型
* @return bool布尔型
*/
public boolean isPalindrome (int x) {
// write code here
//负数不是回文数
//0是回文数
//如果结尾是0,也不是回文数
if(x <0 || (x%10 ==0 && x!=0 )){
return false;
}
//反转一半进行判断
int reversehalf = 0;
while(x>reversehalf){
reversehalf = reversehalf*10+x%10;
x = x/10;
}
return reversehalf == x || x == reversehalf/10;
}
}
js:
/**
*
* @param x int整型
* @return bool布尔型
*/
function isPalindrome( x ) {
// write code here
if(x<0 || (x%10 == 0 && x!=0)){
return false;
}
let temp = 0;
while(x>temp){
temp = temp*10 + x%10;
x = Math.floor(x/10);
}
return x == temp || x == Math.floor(temp/10);
}
module.exports = {
isPalindrome : isPalindrome
};
注意:
- 思路是取后一半反转,和前一半比较,最后return的时候要考虑数位为偶数还是奇数
- js中取余取模比较特殊,取余是%,取模是Math.floor()或parseInt()