leetcode——Palindrome Number 判断整数数字是否为回文(AC)

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.

这道题加了不能使用额外空间的限制,如果没有这个限制的话,我们大可以开辟一个字符串数组把整数的各位数字存储起来,然后使用指针进行判断。在这道题目的要求之下,我们只能每次把首尾的两个数字提取出来进行比较,然后再把这两个数字从原数字钟剔除,继续比较。。。直到所有数字比完,就可得出是回文的结论。个位数提取只需对10取余即可,最高位提取需要将原数字除以10^n次方即可。还有需要注意的是题目要求负数不存在回文。code如下:

class Solution {
public:
    bool isPalindrome(int x) {
		if(x<0)
			return false;
        int base = 1;
		int temp = x;
		while((temp=temp/10) != 0)
			base *= 10;
		temp = x;
		while(temp != 0)
		{
			if(temp%10 == temp/base)
			{
				temp = (temp - temp/base*base)/10;
				base /= 100;
			}
			else
			{
				return false;
			}
		}
		return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值