leetcode刷题记录009-Palindrome Number

文章目录
  1. 1. 题目
  2. 2. 题目分析
  3. 3. 解题过程
  4. 4. 源码地址

题目

题目链接:https://leetcode.com/problems/palindrome-number/description/

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

提示:
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.

题目分析

负数不是回文数字;不能使用额外的空间,即只能使用空间复杂度 O(1) 的方法。
思路一:生成反转整数,对比反转前和反转后的整数。
思路二:循环剥离首数字和尾数字,对比是否收尾数字是否相等。

解题过程

下面是思路一的实现:

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

int y = 0;
int tmp = x;
while(tmp > 0){
y = y*10 + tmp%10;
tmp = tmp/10;
}
return x == y;
}
}

思路二略。

源码地址

https://github.com/voidking/leetcode/tree/master/src/com/voidking/leetcode/question009