Leetcode#9. Palindrome Number(回文数)

来源:互联网 发布:淘宝助手上传宝贝教程 编辑:程序博客网 时间:2024/06/04 08:12

声明:题目解法使用c++和Python两种,重点侧重在于解题思路和如何将c++代码转换为python代码。

题目

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

click to show spoilers.
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)

如果您正在考虑将整数转换为字符串,请注意使用额外空间的限制。

您也可以尝试反转一个整数。 但是,如果您已经解决了“反向整数”问题,则知道反向整数可能会溢出。 你会如何处理这种情况?

有一个更通用的方法来解决这个问题。

解法一 C++版:

注意的点:

  • 负数不是回文数
  • int翻转之后会溢出,要使用long long int。
class Solution {public:    bool isPalindrome(int x) {        if(x < 0)            return false;        long long int sum = 0;        while(x)        {            sum = sum *10 + x % 10;            x = x / 10;        }        if(sum == x)            return true;        else            return false;    }};

我的方法是翻转整个数组的,提交之后在discuss看到一种类似的方法,不过他只翻转得到一半数组:

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

解法二 Python版:

class Solution(object):    def isPalindrome(self, x):        """        :type x: int        :rtype: bool        """        if x<0 or (x != 0 and x % 10 == 0):            return False        now = 0        while x > now:            now = now * 10 + x % 10            x = x / 10        return ( x == now ) or (x == now/10 )

本题github题解链接:https://github.com/xuna123/LeetCode/blob/master/Leetcode%239.%20Palindrome%20Number%EF%BC%88%E5%9B%9E%E6%96%87%E6%95%B0%EF%BC%89%20.md
这道题虽然提交成功了,但是关于题意还是有点不明白:
Do this without extra space.不用额外的空间,有点迷惑?

原创粉丝点击