题目
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
思路
1、判断字符串是否为回文是非常普遍的面试题目了,从两边向中间遍历即可,因此这道题目我们可以首先考虑这种做法
- 通过Integer类的toString方法,将x转为字符串
- 然后从两边向中间扫描即可
代码:
public static boolean isPalindromeII(int x) {
if (x < 0) {
return false;
}
String str = Integer.toString(x);
boolean flag = true;
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
if (str.charAt(i) != str.charAt(j)) {
flag = false;
break;
}
}
return flag;
}
这种做法在LeetCode上是可以ac的(ps:亲测),但是题目规定不允许采用直接转成字符串的做法,.......
2、通过转字符串的思路,我们可以考虑到,是否也可以从两边向中间遍历整数,答案是当然可以
- 获取当前x的长度
- 取最高位和最低位比较,相等继续,不相等返回false
- 取次高位和第二位比较,......
- ......,直接循环len / 2次为止
代码:
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int hp, sp, len, tmp;
// determine the length of x
hp = 1; len = 0; sp = 1; tmp = x;
while (x > 0) {
len ++;
x /= 10;
if (x > 0) {
hp *= 10;
}
}
// check isPalidrome
boolean flag = true;
for (int i = 0; i < len / 2; i ++, hp /= 10, sp *= 10) {
// fetch high number and low number
int high = (tmp / hp) % 10;
int low = (tmp / sp) % 10;
if (high != low) {
flag = false;
break;
}
}
return flag;
}
}
后记
周四收到云os的leader的电话,搞手机安全方面,哈哈,我个人还是很感兴趣的,基本上是c、c++编程,这个有点小郁闷,最近花了两个月的时间学习java,没想到是用c++,不过无所谓了,加油学习就好了
牢记一句话,“以多数人的努力程度之低,根本轮不到拼天赋”