---
# System prepended metadata

title: Question 9. Palindrome Number
tags: [leetcode]

---

###### tags: `leetcode`
# Question 9. Palindrome Number
### Description:
Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
### Solution:
For the first code, it just convert int to string and compare the head and tail until they meet at the middle.
For the second code, it do not convert int to string, it compare the int with reversing the origin half of input with the origin one.
Ex:
"14641"
A: "146"(the last three int and reverse)
B: "146"(the origin first three int)
if the reverse one is equal to the origin one, return true.
### AC code
#### code1
```cpp=
#include "string.h"
class Solution {
public:
    bool isPalindrome(int x) {
        string in = to_string(x);
        int head = 0, tail = in.length()-1, mid;
        if((head+in.length())>>1)
            mid = (head+in.length()+1)/2;
        else
            mid = (head+in.length())/2;
        for(head; head < mid ; head++){
            if(in[head]!=in[tail])
                return false;
            tail--;
        }
        return true;
    }
};
```
#### code2
```cpp=
#include "string.h"
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)
            return false;
        //rhalf: reverse half
        int front = x, back = x, rhalf = 0;
        while(front/10){
            //1464"1"->146"14"
            rhalf = rhalf*10+back%10;
            cout<<"rhalf: "<<rhalf<<endl;
            //1464->146
            back /=10;
            cout<<"back"<<back<<endl;
            //146->1
            front /=100;
            cout<<"front"<<front<<endl;
        }
        return front==0?rhalf==back:back/10==rhalf;
    }
};
```