导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-9.Palindrome Number

题目

Determine whether an integer is a palindrome. Do this without extra space.

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)。
如果你想要将数字转换为字符串,注意题中关于使用额外空间的限制。
你也可以反转数字。但是,如果你做过7. Reverse Integer的话,你就知道反转一个整数可能会导致溢出。你怎样处理这样的情况?
针对本题,有更加通用的解。

首先算出x是几位数,然后不断取最高位和最低位进行比较。如不相等,返回false;如相等,去掉最高位和最低位,循环判断:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0)
return false;

int multiple = 1;
while (x / multiple >= 10)
multiple *= 10;

while (x > 0) {
int high = x / multiple, low = x % 10;
if (high != low)
return false;
x = x % multiple / 10;
multiple /= 100;
}

return true;
}
}

而本题我首先使用的是反转数字,然后判断是否与原数字相等的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public boolean isPalindrome(int x) {
int origin = x, changed = 0;

while (origin > 0) {
changed = changed * 10 + origin % 10;
origin /= 10;
}

return changed == x;

}
}

可能会有溢出问题。但考虑到,回文数字反转后与原数字相等,所以不会溢出;当非回文数字反转溢出时,一般溢出的结果changed不会与x相等……所以可以通过……

参考:
http://my.oschina.net/jdflyfly/blog/283531