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.

解题思路

要判断一个整数是否是回文,首先负数肯定不是,再者,根据Reverse Integer题目可以联想到将整数翻转判断二者是否相等,若相等则为回文.然而题目要求在O(1)的空间复杂度求解一个整数是否是回文,故此只能另辟蹊径:按照回文字符串的判别方法,依次比较前后相对应的文字,但又有一个问题是字符串可以很简单的实现,但对于整数,如果把它转为string再判断又不符合题目条件,所以只好通过变量digit来记录整数位数,比较整数的最高位和最低位,若相等则将整数最高和最低位去掉,继续判断,直至出现不相等或一直对应相等。

C++代码实现

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) {
        return false;
        }
        int digit = 1;   // digit表示x的位数相对应的10进制位 
        int l, r;
        while (digit <= x / 10) {
            digit *= 10;
        }
        while (x != 0) {
            l = x / digit;  // x的最高位
            r = x % 10;     // x的最低位
            if (l != r) {
                return false;
                break;
            } else {
                // 去掉最高位和最低位 
                x %= digit;
                x /= 10;
                digit /= 100; 
            }
        } 
        return true;
    }
};

反思总结

只是单单多一个空间复杂度的要求,就要我们小费周折去判断一个数是否是回文,在这里位数的表示以及将整数不断去除最高最低位刚刚好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值