Leetcode 9. Palindrome Number

题目

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.

分析

判断一个整数是否是回文数。首先负数不是回文数。之后判断前后各个位的数字是否相同。
我用的一个数组去保存各个数位的数字。
还可以直接计算其反过来的数,但是确保是否溢出。

bool isPalindrome(int x) {
    if(x<0)return false;
    int num[20],length=0;
    bool answer=true;
    while(x>0)
    {
        num[length]=x%10;
        x=x/10;
        length++;
    }
    for(int i=0;i<length/2;i++)
    {
        if(num[i]!=num[length-1-i])
        {
            answer=false;
            break;
        }
    }
    return answer;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,792评论 0 33
  • 那年,石油局搬迁,我们学校高中部也由青海迁到美丽的敦煌,校长也换了。 我正好上高三,大约那时候孩子多,父母对正上高...
    萝卜英阅读 316评论 1 2
  • 万事万物皆有度,任何事不可太平淡也不可太过,然而过与不过之间的度,是让人最难以把握的,好比追一个女孩,无动于衷可能...
    反转的钟阅读 738评论 0 2
  • 今天端午节,早上也是早早起床,煮了白粥,炒了一个菜。然后就是开始早上的功课《能量朗读》,在房间读的,昭阳公主已经醒...
    耕读传家林亮伟阅读 189评论 0 1