[LeetCode 题解]: palindromes

本文介绍了一种不使用额外存储空间判断整数是否为回文数的方法,通过将低位部分翻转并与高位部分对比来实现。讨论了如何避免整数翻转时的溢出问题,并给出了具体的C++实现代码。

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.

题解: 

求解回文数(提示,回文数是指一个数A,将其翻转之后的到数B,且有A=B, 例如: 1,11 , 131, 65356 等)

(1) 回文数是自然数,最小的回文数为0

(2) 不能使用额外存储空间, 因此不能采用字符串翻转来做。

(3) 不能直接将整个数翻转过来,可能出现“溢出”。

 

受到条件(3)的启发, 既然不能整个翻转,能否部分翻转呢? 尝试之后发现有如下结论:

 

将数A分成左右相等的部分(高位部分A1,低位部分A2):

特别的: 如果A的长度为奇数,那么处于中间数位的数字对于回文比较不会产生影响。因此可以忽略。

将A2 翻转,得到A2‘ ,那么有

若A1 = A2’ , A为回文数

否则A不是回文数。

class Solution {
public:
    bool isPalindrome(int x) {
        int temp=x,n=0,len=0,i;
        if(x<0) return false;

        while(temp>0)    //计算数字长度
        {
            temp/=10; len++;
        }

        for(i=0;i<len/2;i++)   //二分, 高位保留,低位翻转相乘 
        {
            n = n*10 + x%10;
            x/=10;
        }
        if(len%2) x/=10;   // 如果是奇数位,中间数字可以忽略
        return (n==x);
    }
};

 

转载于:https://www.cnblogs.com/double-win/p/3752606.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值