leetcode [#9]

目录

题目

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.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0 || (x != 0 && x % 10 == 0)) return false;
if(x == 0) return true;
int tmp = 0;
int x0 = x;
while(x > 0){
tmp = tmp * 10 + x % 10;
x = x / 10;
}
return tmp == x0 ? true : false;
}
}

注意事项

  1. 负数不可能是回文的,不为零且为10的倍数的数不可能是回文的。
  2. 对于其他情况,使用tmp变量来进行累加,从x的个位开始,进行求和。比较最终x和tmp的大小关系。
  3. 不可能完全不用额外空间。题目的意思应该是不开辟线性增长的空间,但使用一个变量tmp应该是可以的。