DEV Community

Cover image for Palindrome Number
FakeStandard
FakeStandard

Posted on • Edited 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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Example 3

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Enter fullscreen mode Exit fullscreen mode

Explanation

給定一個 x 的整數,如果是回文則返回 true,否則 false

回文的定義是不論從頭或從尾開始,讀起來是一樣的,例如 1211221 是回文,但 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;
}
Enter fullscreen mode Exit fullscreen mode

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
or follow my GitHub
or buy me a coffee ⬇️ I'd appreciate it.

Buy-me-a-coffee


Top comments (0)