回文数

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

  • -231 <= x <= 231 - 1

示例 1:

  • 输入:x = 121
  • 输出:true

解题思路:将整数反转,然后和原整数进行对比。

Java实现

    public static void main(String args[]){
        int x = 121210;
        System.out.println(isPalindrome(x));//false
        System.out.println(isPalindrome2(x));//false

     }

    //方法1
    public static boolean isPalindrome(int x) {
        if (x<0 || x>Math.pow(2,31)-1){
            return false;
        }
        int y =x;
        long result = 0;
        while (y != 0){
            int temp = y%10;
            result = result*10+temp;
            y /= 10;
        }
        return result == x;
    }

    //方法2
    public static boolean isPalindrome2(int x) {
        if (x<0 || x>Math.pow(2,31)-1){
            return false;
        }
        String str1 = String.valueOf(x);//将int类型转换为String类型
        StringBuilder sb = new StringBuilder(str1);
        String result = sb.reverse().toString();//反转字符串

        if (result.equals(str1)){
            return true;
        }else {
            return false;
        }
    }

JS实现

//方法1
var isPalindrome = function(x) {

  var res = x.toString().split("").reverse().join("");

  if (res == x) {
    return true;
  }else{
    return false;
  } 

}
console.log(isPalindrome(121121));//true

//方法2
var isPalindrome2 = function(x) {
  if (x<0 || x>Math.pow(2,31)-1) {
    return false;
  }
  let y = x;
  let res = 0;
  while(y != 0){
    res = res*10 + y%10;
    y = ~~(y/10);
  }
  return res == x;

}
console.log(isPalindrome2(121121));//true
console.log(isPalindrome2(12112));//false

 

posted @ 2021-09-18 09:27  rissa  阅读(154)  评论(0)    收藏  举报

记录学习笔记,会有很多是参考重复,如有侵权,联系删除