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的方法,求的转换后的数字,然后比较是否相等。提示说这样有溢出的问题,想了想感觉问题不大。因为首先输入必须是一个合法的int值,负数直接返回false,对于正数,假设输入的int是一个palindrome,reverse之后依然不会溢出,所以正常返回true;所以如果转换后溢出了,证明肯定不是palindrome,溢出后的数字跟输入一般不相同(想不出相等的情况-_-!,求指点),所以返回了false。 

方法二:从两头依次取数字比较,向中间推进。

C代码如下:

bool isPalindrome(int x) {
    int i, j;
	if(x < 0)
		return 0;
	else if(x < 10)
		return 1;
	int base = 1;
	int save;
	save = x;
	for(i = 0; x / base >= 10 ; i++)
		base *= 10;
	for(j = 0; i >= j; j++)
	{
		if(save / base != x % 10)
			return 0;
		else
		{
			save %= base;
			x /= 10;
			base /= 10;
			i--;
		}
	}
	return 1;
}

小结:

(1)注意所有可能发生的变量溢出的情况,如果第一个for循环里的终止条件是x/base != 0,则x足够大时base可能溢出。

(2)如果需要一直用到10的次方这样的数,可以一开始就算出来并保存在变量里,而不必每次都调用pow()函数,减少计算量。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值