LeetCode 9.Palindrome Number

题目:

Determine whether an integer is a palindrome. Do this without extra space.

判断一个整形数字是不是回文。附加条件是不能用额外空间。

分析与解答:

如果没有附加条件,那么一个容易实现的做法是将数字每次除以10,余数依次存入数组,再从头和尾部依次检查看是否相等。复杂度O(n)。

不能用额外空间的话,就把数字倒转吧,正好利用了reverse integer这个方法。这里就体现了上个方法的简单之处,不需要考虑overflow的问题。

关于负数可不可以是回文数的例子,我一开始把它当做是的,但结果是WA,发现不行。

<span style="font-size:10px;">class Solution {
public:
    bool isPalindrome(int x) {
    if (x<0)
		return 0;
	int result = 0, mod = 0,tx=x;
	while (x >= 10) {
		mod = x % 10;
		if (result > INT_MAX / 10)
			return 0;
		result = result * 10 + mod;
		x = x / 10;
	}
	if (result > INT_MAX / 10)
		return 0;
	result = result * 10 + x;
	return (result==tx);
    }
};</span>


你可能感兴趣的:(Math)