The photo of the problem
1. the analysis of the problem:
First we can easily know if the number smaller than 0,it can not be the palindrome number.
We can not compare with the first digit with the last digit,so we need come up with a method to transfer the form so that we can compare easily,then if we transfer the number to an array or vector sucessfully,we can compare the beginning digits with the ending digits easily,
but before this, we need divide it into two situations:
the number of the digit of the number is the odd or even.
we assume size=the number of the digit(same as the length of vector),
and then
if the size is odd:
we compare the vec[0]with vec[size-1],vec[1]with vec[size-2]......vec[(size-1)/2]with vec[(size+3)/2],leave size[n+1] alone.
if all comparisions equate so the number is palindrome number.
so we have codes as:
if(size%2!=0){
int mid=(size+1)/2;
for (int i=0;i<mid;i++){
if (vec[i]!=vec[size-1-i]){
return false;
}
}
return true;
}
if the size is even:
we campare the vec[0]with vec[size-1],vec[1]with vec[size-2]......vec[size/2]withvec[(size/2)+1],if all comparisions equate so the number is palindrome number.
int mid=size/2;
for (int i=0;i<=mid;i++){
if(vec[i]!=vec[size-1-i]){
return false;
}
}
return true;
so totally we have the complete codes as:
class Solution {
public:
bool isPalindrome(int x) {
if (x<0){
return false;
}//the situation of minus
string str=to_string(x);
vector<int>vec;
for(char digit :str){
vec.push_back(digit-'0');
}
int size=vec.size();
if(size==1){
return true ;
}//the situation of one-digit
if(size%2!=0){
int mid=(size+1)/2;
for (int i=0;i<mid;i++){
if (vec[i]!=vec[size-1-i]){
return false;
}
}
return true;
}//the situation of odd
int mid=size/2;
for (int i=0;i<=mid;i++){
if(vec[i]!=vec[size-1-i]){
return false;
}
}
return true;
//the situation of even
}
};
//fist discuss the situation od minus,if the number smaller tham 0,then it can not be a palindrome
//we use the function 'string str= to_string(x)' to change the form of x from int to string
//then define a vector 'vecctor<int>vec;
//then we need get each char digit from str
//by using 'result.push_back(digit-'0')' we can get a vector full of integers.
//if there is only one element in the vector ,then it should fit the requirement and is a palindrome.
Top comments (0)