LeetCode 回文数 [简单]
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
题目分析
解法1:
题目已经给了提示,能不使用字符串完成吗?那么第一种就是字符串的操作。操作的方式与很多种,可以使用 StringBuilder 或者 StringBuffer 的反转,也可以将字符串转换为 字符数组,然后比较
解法2:
数学解法,通过取整数和余数获取证数种对应的数字进行比较
解法3:
取出后半段数据进行翻转,然后和前面半段进行比较
可以参考大神的解答:https://leetcode-cn.com/problems/palindrome-number/solution/dong-hua-hui-wen-shu-de-san-chong-jie-fa-fa-jie-ch/
代码实现
public class LeetCode_08_PalindromeNumber {
public static void main(String[] args) {
System.out.println(isPalindrome(1111));
System.out.println(isPalindrome02(1111));
System.out.println(isPalindrome03(1111));
}
public static boolean isPalindrome03(int x) {
if (x < 0) {
return false;
}
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) {
return false;
}
x = (x % div) / 10;
div /= 100;
}
return true;
}
public static boolean isPalindrome02(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int resNumber = 0;
while (x > resNumber) {
resNumber = resNumber * 10 + x % 10;
x /= 10;
}
return x == resNumber || x == +resNumber / 10;
}
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
String res = (new StringBuilder(x + "")).reverse().toString();
return (x + "").equals(res);
}
}