DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Palindrome Number
FakeStandard
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.
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

ๅ›žๆ–‡็š„ๅฎš็พฉๆ˜ฏไธ่ซ–ๅพž้ ญๆˆ–ๅพžๅฐพ้–‹ๅง‹๏ผŒ่ฎ€่ตทไพ†ๆ˜ฏไธ€ๆจฃ็š„๏ผŒไพ‹ๅฆ‚ 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;
}
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)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.