LeetCode从零刷起 (9. Palindrome Number)

LeetCode(9. Palindrome Number)

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. 负数不会是回文。
  2. 由于本题要求"Do this without extra space",在我理解为空间复杂度应该控制在O(1)。所以本题不能用string类型转换来做。

解题思路:

本题是判断一个integer是否为回文。我的做法是,从integer的两边开始往中间走来判断,设置一个left变量和一个right变量。当最后剩余的数据位数小于等于二的时候,进行一下简单的判断就可以了。
C++代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false; //negative number is not a palindrome
        if (x >= 0 && x <= 9) return true;
        //to get the length of digits
        int len = 0, x1 = x;
        while (x1 > 0){
            len++;
            x1 /= 10;
        }
        //from head and from tail to check
        int left, right;
        while (len > 2){
            left = x / pow(10,len-1);
            right = x % 10;
            if (left != right)
                return false;
            x = (x - left*pow(10,len-1)) / 10;
            len -= 2;
        }
        if (len == 1)
            return true;
        else{ // len == 2
            if (x/10 == x%10)
                return true;
            else 
                return false;
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 我从iOS5开始编写iOS的应用,应该算是起步比较晚的了。那个时候我大二,因为觉得学院所教的用swing写的PC客...
    danisfabric阅读 2,052评论 3 11
  • 第九章 你的出现 李教练:今天我们介绍一位新同学唐南,马上就要去新加坡当教练了,同学们多像他学习,好自己训练吧!...
    吖吖唅阅读 140评论 0 0
  • 我们每个人都有心情不好的时候,怎么去解决呢? 心情不好,心里压抑,让我们来换一个思维方式,就是身体内於堵了,就如同...
    开心的灵通阅读 440评论 1 1
  • 讲真,一直不明白老家方言里的zuxie,究竟普通话里哪两个字可指,直到初中学习鲁迅先生的《社戏》,“做社”二字跃于...
    十二月的白菜阅读 1,734评论 10 15