LeetCode第九题:Palindrome Number(C++)
Palindrome Number
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.
Follow up:
Coud you solve it without converting the integer to a string?
题目中说明了不能使用将整数转换成字符串的办法,所以可以采用将int型整数逆转的办法,如果逆转后与原始整数相等,即为回文数,这是解题思路一:
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
{
return false;
}
long origin = x;
long reverse = 0;
while(x)
{
int num = x % 10;
reverse = reverse * 10 + num;//逆转整数
x/=10;
}
if(reverse == origin)
{
return true;
}
else
{
return false;
}
}
};
性能:
解题思路二:以此将整数的低位至高位数存入vector容器中,然后从二端向中间开始比较是否相等,相等即为回文数,不相等即不为回文数,如下:
class Solution {
public:
bool isPalindrome(int x) {
vector<int> vec;
if(x < 0)
{
return false;
}
while(x!=0)
{
vec.push_back(x%10);//依次将个位至最高位push到vector中
x/=10;
}
int len = vec.size() - 1;
for(int i=0;i<len;i++,len--)
{
if(vec[i] == vec[len])//二端遍历比较
{
continue;
}
else
{
return false;
}
}
return true;
}
};
性能:
总结:
判断回文数直观的方法是转化成字符串,直接从二端遍历字符串即可得出结果;
方法一:直接逆转整数,来比较是否相等,类似于转化成字符串的方法,效率高,方法简洁;
方法二:使用了容器vector,二端遍历容器,效率不高。
欢迎大家,留言,谢谢。