[LeetCode] Palindrome Number 解题报告

来源:互联网 发布:ubuntu怎么安装wps 编辑:程序博客网 时间:2024/05/13 21:08

[题目]
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.

[中文翻译]
确定整数是否是回文。 不使用额外的空间。
提示:
负整数是回文吗? (如,-1)
如果你正在考虑将整数转换为字符串,请注意不使用额外空间的限制。
您也可以尝试反转整数。 但是,如果已解决了“Reverse Integer”的问题,则知道反向整数可能溢出。 你将如何处理这种情况?
有一个更通用的方法来解决这个问题。

[解题思路]
先反转整数,然后比较反转的整数是否与原整数相同。对于溢出的情况,使用long long即可解决。不是很确定,这种方法是否违反了不适用额外空间的限制。

看Discuss的时候,发现其实整数只需要反转一半即可。

[C++代码]

class Solution {public:    bool isPalindrome(int x) {        if (x < 0)            return false;        long long y = 0;        int tmp = x;        while (x > 0) {            y = y * 10 + x % 10;            x = x / 10;        }        return tmp == y;    }};
0 0
原创粉丝点击