leetcode—Palindrome Number

来源:互联网 发布:远程网络打印机 编辑:程序博客网 时间:2024/06/04 22:18

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.

class Solution {    public boolean isPalindrome(int x) {        if(x<0 || (x!=0 && x%10==0)) return false;        int res = 0;        while(x>res){            res = res*10+x%10;            x = x/10;        }        if((res==x) ||(res/10==x)){            return true;        }else            return false;    }}

**如何判断一个数字是不是回文数呢?就是通过把这个数字分成两半,这两部分相等或则说一个数字除以10等于另外一个数字,那么则代表这个数字是回文数,那么如何把这个数字分成两半呢?
while(x>res){
res = res*10+x%10;
x = x/10;
}这个循环语句的作用就是将这个回文数字从中间分成两个部分**