[Leetcode ] 106. 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.

解题之法

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int div = 1;
        while (x / div >= 10) div *= 10;
        while (x > 0) {
            int left = x / div;
            int right = x % 10;
            if (left != right) return false;
            x = (x % div) / 10;
            div /= 100;
        }
        return true;
    }
};

分析

这道验证回文数字的题不能使用额外空间,意味着不能把整数变成字符,然后来验证回文字符串。而是直接对整数进行操作,我们可以利用取整和取余来获得我们想要的数字,比如 1221 这个数字,如果 计算 1221 / 1000, 则可得首位1, 如果 1221 % 10, 则可得到末尾1,进行比较,然后把中间的22取出继续比较。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 白轩人生中最离奇的事情,发生在他二十一岁那年。 那一年,白轩刚刚毕业,说好的璀璨人生,不会那么早就到来。 白轩在出...
    宋小君阅读 8,725评论 19 85
  • 总有一些人喜欢做什么事都要联想到一些道理。参加一个培训,第一个周要进行所谓的拓展训练,其实就是军训。每练一个项目都...
    不如疯一场阅读 1,567评论 0 0
  • 吵架了,偶尔还是有小插曲,说沟通少了,每天抱着手机,一点意思也没有,影响夫妻生活。心想,其实我一天到晚真心玩手机的...
    幽兰依依阅读 1,045评论 0 1
  • 睡后收入 赚钱的最正确姿势是躺着。 普遍来看,普通人的赚钱能力在越来越快地提高: 普遍来看,普通人在生活必需上的开...
    陈东Growth阅读 1,832评论 0 0

友情链接更多精彩内容