【leetcode】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.


题解:

首先,负数不算回文的整数。

每次比较头尾两个元素是否相等,如果不想等,返回false,如果相等,继续比较下一组,直到头尾相遇。

这里用模10的方法获得整数的最后一位数,用除法获得整数的第一位数,并在比较完这两个数后将头尾的两个数都去掉。例如12321的比较过程如下:

1和1比较,12321->232;

2和2比较,232->3;

3和3比较,3->0 结束。

代码如下:

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3           if(x < 0)
 4               return false; 
 5           long div = 1;
 6           while(x / div > 0)
 7               div *= 10;
 8           
 9           div = div / 10;
10           while(x > 0){
11               int first = x/(int)div;
12               int last = x%10;
13               if(first != last)
14                   return false;
15               x = x % (int)div;
16               x = x/10;
17               div /= 100;
18               
19           }
20           return true;
21     }
22 }

要注意的一点就是虽然x是int型,但是第6,7行的循环可能让div超过int型的界,所以将div定义为long型。还有一种方法是在x>=10的时候就跳出循环,div始终比x小,就不会越界了。

原文地址:https://www.cnblogs.com/sunshineatnoon/p/3838440.html