[leetcode]Palindrome Number

本文探讨如何解决LeetCode中的PalindromeNumber问题,包括负数是否为回文数的定义,以及不使用额外空间的通用解决方案。通过分析不同方法,如字符串转换、反转整数等,文章提供了一个有效且符合限制条件的解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新博文地址:[leetcode]Palindrome Number

http://oj.leetcode.com/problems/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.

 

写道
Hint:
Don’t be deceived by this problem which seemed easy to solve. Also note the restriction of doing it without extra space. Think of a generic solution that is not language/platform specific. Also, consider cases where your solution might go wrong.

Solution:
First, the problem statement did not specify if negative integers qualify as palindromes. Does negative integer such as -1 qualify as a palindrome? Finding out the full requirements of a problem before coding is what every programmer must do. Here, we define negative integers as non-palindromes.

The most intuitive approach is to first represent the integer as a string, since it is more convenient to manipulate. Although this certainly does work, it violates the restriction of not using extra space. (ie, you have to allocate n characters to store the reversed integer as string, where n is the maximum number of digits). I know, this sound like an unreasonable requirement (since it uses so little space), but don’t most interview problems have such requirements?

Another approach is to first reverse the number. If the number is the same as its reversed, then it must be a palindrome.This seemed to work too, but did you consider the possibility that the reversed number might overflow?
We could construct a better and more generic solution. One pointer is that, we must start comparing the digits somewhere. And you know there could only be two ways, either expand from the middle or compare from the two ends. 

no more extra space?我还以为一点的空间都不能有呢,木想到还是有o(1)个空间的。看了提示之后,算法自然就想到了:(不过还是人家的代码好看。。。。贴出来晒晒)

	public boolean isPalindrome(int x) {
		if(x < 0){
			return false;
		}
		int divisor = 1;
		//为了得到最高位的数字,要选择合适的除数
		while(x / divisor >= 10){
			divisor *= 10;
		}
		while(x != 0){
			int high = x/divisor;
			int low = x%10;
			if(high != low){
				return false;
			}
			x = (x - high * divisor) / 10;
			divisor /= 100;
		}
		return true;	
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值