一、题目还原
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
二、解题思路
Solution 1
① 利用整数反转进行比较
Solution 2
① 转换成字符串,用reverse函数进行比较
三、代码展示
① main函数
public static void main(String[] args) {
int x = 12344321;
System.out.println("isPalindrome == "+isPalindrome(x));
System.out.println("isPalindrome2 == "+isPalindrome2(x));
}
② isPalindrome方法函数
public static boolean isPalindrome(int x){
int s = x;
if(x < 0){
return false;
}
long result = 0;
while(x > 0){
result = result * 10 + x % 10;
if(result > Integer.MAX_VALUE){
return false;
}
x /= 10;
}
return s == (int)result;
}
控制台输出:
isPalindrome == true
Process finished with exit code 0
③isPalindrome2方法函数
public static boolean isPalindrome2(int x) {
StringBuilder stringBuilder = new StringBuilder(x+"");
if(stringBuilder.toString().equals(stringBuilder.reverse().toString())){
return true;
}
return false;
}
控制台输出:
isPalindrome2 == true
Process finished with exit code 0
四、自我总结
本题是LeetCode第九题,难度为简单,涉及到的算法在之前 题目中都有涉及,算是巩固基础知识吧
- 博主最近也将刷题的代码上传到github中,欢迎各位大佬们指点一二
Github仓库地址:https://github.com/w735937076/LeetCode