## DEV Community ๐ฉโ๐ป๐จโ๐ป

FakeStandard

Posted on • Updated on

# Palindrome Number

#9.Palindrome Number

### Problem statement

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 1

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

Example 2

``````Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
``````

### Explanation

็ตฆๅฎไธๅ `x` ็ๆดๆธ๏ผๅฆๆๆฏๅๆๅ่ฟๅ `true`๏ผๅฆๅ `false`

ๅๆ็ๅฎ็พฉๆฏไธ่ซๅพ้ ญๆๅพๅฐพ้ๅง๏ผ่ฎ่ตทไพๆฏไธๆจฃ็๏ผไพๅฆ `121` ๅ `1221` ๆฏๅๆ๏ผไฝ `123` ไธๆฏ

### Solution

้้ก่ฆ่ๆฎ็ๅฐๆนๆฏๅๆ็้ทๅบฆ๏ผๅถๆธ้ทๅบฆ็ๅๆๅๅฒ็บๅทฆๅณๅฉ็ญๅๆๆฏ่ผๅฅฝๅคๆท๏ผๅฅๆธ้ทๅบฆ็ๅๆๆๅพๆ็ไธไธญ้็ๆธ๏ผๅฎไธ้่ๅถไปๆธๅฐๆ๏ผไธ้ก็ฎๆๅพ็ Follow up ้ๆๅฐ่ฝๅฆๅจไธๅฐๆธๅญ่ฝๆๆๅญไธฒ็ๆๆณไธไพ่งฃ๏ผไพ็งๅ่ฟฐ็ๅๆๅ้กๆ๏ผๆญค้กๅฏไฝฟ็จ็ฎ่ก้็ฎๅญ๏ผArithmetic operators๏ผไพ่งฃใ

ไธ้ๅงๅ้ๆฟพไธไบ็นๅฎ็ๆขไปถ

• ๅคๆท `x` ๆฏๅฆ็บ 0๏ผๅฆๆๆฏ return true
• ๅคๆท `x` ๆฏๅฆๅฐๆผ 0 ๆ่็บ 10 ็ๅๆธ๏ผๅฆๆๆฏ return false

ๆฅ่ๅท่ก `while` ่ฟดๅ็ดๅฐๆขไปถๆ็ซ๏ผๆๅพ return `x` ่ๆทๅๅบ็ `reverseNum` ๆฏๅฆ็ธ็ญใ

``````public bool IsPalindrome(int x)
{
if (x == 0)
return true;

if (x < 0 || x % 10 == 0)
return false;

int reverseNum = 0;

while (x > reverseNum)
{
reverseNum = reverseNum * 10 + x % 10;
x /= 10;
}

return x == reverseNum || x == reverseNum / 10;
}
``````

### Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article ๐ท ๐ป ๐ผ

If you like it, please don't hesitate to click heart button โค๏ธ
or click like on my Leetcode solution