力扣——9 [回文数](https://leetcode.cn/problems/two-sum/)
给你一个整数 x
,如果 x
是一个回文整数,返回 true
;否则,返回 false
。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
- 例如,
121
是回文,而123
不是。
示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入:x = 10
输出:false
解释:从右向左读, 为 01 。因此它不是一个回文数。
提示:
-231 <= x <= 231 - 1
进阶:你能不将整数转为字符串来解决这个问题吗?
package com.moli.easy;
/**
* 回文数
* 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
* 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
* 例如,121 是回文,而 123 不是。
*
* @author moli
*/
public class PalindromicNumberSolution {
public static void main(String[] args) {
boolean palindrome = isPalindrome(Integer.MAX_VALUE);
System.out.println(palindrome);
}
/**
* 判断一个数是否是回文数
* <p>
* 这次做题去看了一下位运算符的操作
* 发现^运算自己永远都是0
* 这样就可以将x翻转后再^x,值为0 就说明是回文数
* <p>
* 如何翻转却变成了难题,于是就在网上搜了一下(原来这也是这道题的考点)
* 一个数不停地%10,得到个位数,然后除以10后重复%10进行翻转操作
* 但是可能会存在溢出风险,所以使用long类型接受
* <p>
* <p>
* 时间复杂度:O(log(n)),对于每次迭代,会将输入除以 10,因此时间复杂度为 O(log(n))。
* 空间复杂度:O(1)。我们只需要常数空间存放若干变量。
* <p>
* 果然这样处理效率还是不错的,在平台中击败了98.48%的用户
*
* @param x
* @return
*/
public static boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int y = x;
long n = 0;
while (x != 0) {
n = n * 10 + x % 10;
x = x / 10;
}
int reverse = (int) n == n ? (int) n : 0;
return (y ^ reverse) == 0;
}
/**
* 作者:力扣官方题解
* 链接:https://leetcode.cn/problems/palindrome-number/solutions/281686/hui-wen-shu-by-leetcode-solution/
* 来源:力扣(LeetCode)
* 官方解题思路
*
* @param x
* @return
*/
public boolean isPalindrome1(int x) {
// 特殊情况:
// 如上所述,当 x < 0 时,x 不是回文数。
// 同样地,如果数字的最后一位是 0,为了使该数字为回文,
// 则其第一位数字也应该是 0
// 只有 0 满足这一属性
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
// 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
// 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
return x == revertedNumber || x == revertedNumber / 10;
}
}
源码访问:https://gitee.com/moliyy/leet-code.git