题目
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
翻译
判判断一个数是否为回文数,并且不可以使用额外存储空间
解题思路
- 对于回文数判断,我最开始想到的是搞一个
int
型变量temp
,用temp
来存储输入x
的反转,接着将temp
与x
进行比较,最后通过比较结果来输出true
或false
。但是题中明确给出了不可以使用额外存储空间的条件,因此此方式不可行- 使用字符串,这个方式就很简单了,先把字符串反转,然后判断两者是否相等,相等即为回文数字
- 查看了下官方答案,用了一种很巧妙的方式,通过以此去比较指定数字的最高位和最低位是否相等来确定是不是回文数字
解法一
使用字符串来实现,代码比较简洁,也很好理解,源码如下:
/**
* 直接使用字符串的方式
* @param x
* @return
*/
public static boolean isPalindrome_2(int x) {
String b = String.valueOf(x);
StringBuilder before = new StringBuilder(b);
String after = before.reverse().toString();
return b.equals(after);
}
解法二
使用官网提供的解题思路,逐次去判断给定数字的最高位和最低位是否相等来决定是否为回文数字
-
①创建两个int变量left和right;
-
②left表示当前数x的最高位数字,right表示当前数x的最低位数字;
-
③若 left == right,则将当前数x去掉最高位和最低位,并且继续执行②,直至
x == 0
;
public static boolean isPalindrome(int x) {
int length = 1;
// 负数 越界肯定不是回文
if (x < 0 || x > Integer.MAX_VALUE) {
return false;
}
while(x / length >= 10) {
length *= 10;
}
while (x != 0) {
// x 的最高位
int left = x / length;
// x 的最低位
int right = x % 10;
// 有不相等的
if (left != right) {
return false;
}
// 去掉已经比较过得最高位和最低位 如 12345 变成 234
x = (x % length) / 10;
// 去除最高位和最低位之后 x 的长度也相应要减少
length /= 100;
}
return true;
}
Github地址:https://github.com/Bylant/LeetCode
优快云地址:https://blog.youkuaiyun.com/ZBylant
微信公众号