LeetCode Algorithm 0009 - Palindrome Number (Easy)

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/darkrabbit/article/details/82791287

LeetCode Algorithm 0009 - Palindrome Number (Easy)

Problem Link: https://leetcode.com/problems/palindrome-number/description/



Description

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

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

Follow up:

Coud you solve it without converting the integer to a string?


Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/palindrome-number/description/

namespace P9PalindromeNumber
{
    class Solution
    {
        public:
        bool isPalindrome(int x)
        {
            // 题目要求不能使用 `string`

            // minus or last num is zero.
            if (x < 0 || (x != 0 && x % 10 == 0))
            {
                return false;
            }

            // only one digit
            if (x < 10)
            {
                return true;
            }

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

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


猜你喜欢

转载自blog.csdn.net/darkrabbit/article/details/82791287