[Leetcode从零开刷]9. Palindrome Number

来源:互联网 发布:手机淘宝2016所有版本 编辑:程序博客网 时间:2024/06/03 03:14

题目来源:
leetcode
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.

翻译:判断一个数是否是回文数,不要用额外的space。
一些提示:
负数有回文么?(例子:-1)
如果你正在考虑用字符串,那肯定回用到额外的空间。
可以尝试考虑用反转整数的方法,如果你做过那个题,应该会知道那个题容易越界,那如何解决?
有更一般的方法来解决这个问题。

解题:
也不是很清楚额外的空间指的是什么,也不是很清楚overflow到底是个什么样子,写博客简直就是记录了现在的自己有多菜~~
提示里写到如果写过翻转整数,应该会有点想法。
思路:
先搞清楚回文数长啥样:
应该有两种:
1234554321
123454321
负数明显不可能是回文数
结尾是0的也不会是回文数
单个数应该是回文数

然后看着数的前半部分和后半部分是相反的,如果将后半部分取反转,再和前半部分作比较就可以知道是不是回文数了。

java:

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