题目:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
不转换为字符串
思路:
将int型数倒置,然后比较是是否相同,倒置的时候要是否越界。
代码:
bool isPalindrome(int x){
if (x<0)
{
return false;
}
bool res =false;
int mod = 0;
int con = x;
double new =0;
while (con >0)
{
mod = con %10;
con =con/10;
new =new *10 + mod;
}
if(x == new)
{
res = true;
}
return res;
}
效率:
效率还行,挺简单的一个题目,应该还有其他解法。