---
# System prepended metadata

title: LeetCode 9. Palindrome Number
tags: [Leetcode]

---

---
title: 'LeetCode 9. Palindrome Number'
disqus: hackmd
---

# LeetCode 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 a palindrome while 123 is not.

## Example

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

## Constraints

-2^31^ <= x <= 2^31^ - 1

## Answer

此題可藉由取餘數將每個數字都抓出，然後再做前後比對，而INT最大就是10位數。

```Cin=
bool isPalindrome(int x) {
    if(x < 0){return false;}
    int *temp = (int*)malloc(sizeof(int)*10);
    int i = 0, cnt = 0;
    while(x != 0){
        temp[cnt] = x % 10;
        x /= 10;
        cnt = x == 0 ? cnt : cnt + 1;
    }
    while(i < cnt){
        if(temp[i] != temp[cnt]){
            free(temp);
            return false;
        }
        i++;
        cnt--;
    }
    free(temp);
    return true;
}
```


另一解法可以取餘數來計算倒著的新數，若兩數相等即return true。記得考慮overflow的情況。

```Cin=
bool isPalindrome(int x){
    if(x < 0){return false;}
    int opr = x, cmp = 0, tmp = 0;
    while(opr){
        tmp = opr%10;
        if(cmp > (INT_MAX - tmp)/10){return false;}
        else{
            cmp = cmp * 10 + tmp;
            opr /= 10;
        }
    }
    return cmp == x;
}
```

## Link
https://leetcode.com/problems/palindrome-number/
###### tags: `Leetcode` 
