9. 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.
class Solution {
public:
bool isPalindrome(int x) {
}
};
解题思路:
-
自己的解题思路
首先取出前后两个数字,然后比较这两个数字;之后,去掉这两个数字后,继续比较。
-
别人的解题思路
对我的程序一个改进。
还有一个介绍了只需要遍历一半左右的长度的数,就能比较出是否为回文数。
注意,这是
reverse()
整数的思路。
reverse()
时,可能存在溢出的风险。对于本题,虽然也能得出正确的答案,但是不推荐。
学习收获:
-
注意, LeetCode 此题认为负数统一都不是回文数(当然,别的地方可能认为负数也有可能是回文数)
-
使用了 log10() 。这就要求里面的数字大于 0 。
附件:程序
1
、自己的程序:
class
Solution
{
public
:
bool
isPalindrome
(
int
x
)
{
if
(
x
<
0
)
return
false
;
if
(
x
==
0
)
return
true
;
int
digits
=
0
;
int
tem
=
x
;
digits
=
int
(
log10
(
x
));
tem
=
x
;
while
((
digits
>
0
)
&&
(
tem
%
10
)
==
(
tem
/
int
(
pow
(
10
,
digits
))))
{
tem
-=
tem
%
10
+
(
tem
%
10
)*
int
(
pow
(
10
,
digits
));
tem
/=
10
;
digits
-=
2
;
}
return
(
digits
<=
0
)?
true
:
false
;
}
};
2
、别人的程序
对自己程序的改进版
class
Solution
{
public
:
bool
isPalindrome
(
int
x
)
{
if
(
x
<
0
)
return
false
;
int
d
=
1
;
// divisor
while
(
x
/
d
>=
10
)
d
*=
10
;
while
(
x
>
0
)
{
int
q
=
x
/
d
;
// quotient
int
r
=
x
%
10
;
// remainder
if
(
q
!=
r
)
return
false
;
x
=
x
%
d
/
10
;
d
/=
100
;
}
return
true
;
}
};
这题最好的解题方法,一个只需要过半,就可以
class
Solution
{
public
:
bool
isPalindrome
(
int
x
)
{
//
一个边界条件都不能少
if
(
x
<
0
||
(
x
!=
0
&&
x
%
10
==
0
))
return
false
;
int
sum
=
0
;
while
(
x
>
sum
)
{
sum
=
sum
*
10
+
x
%
10
;
x
=
x
/
10
;
}
return
(
x
==
sum
)
||
(
x
==
sum
/
10
);
}
};