回文数
给你一个整数 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
记录学习笔记,有其他参考,如有侵权,联系删除
本文来自博客园,作者:rissa,转载请注明原文链接:https://www.cnblogs.com/rissa/p/15307187.html

浙公网安备 33010602011771号