Press "Enter" to skip to content

花花酱 LeetCode 9. Palindrome Number

Problem

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:

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

Solution 1: Convert to string (cheating)

Time complexity: O(log10(x))

Space complexity: O(log10(x))

C++

Solution 2: Digit by Digit

Every time we compare the first and last digits of x, if they are not the same, return false. Otherwise, remove first and last digit and continue this process.

How can we achieve that via int math?

e.g. x = 9999, t = pow((10, int)log10(x)) = 1000

first digit: x / t, last digit: x % 10

then x = (x – x / t * t) / 10 removes first and last digits.

t /= 100 since we removed two digits.

x / t = 9 = 9 = x % 10, 9999 => 99

9 = 9, 99 => “”

Time complexity: O(log10(x) / 2)

Space complexity: O(1)

C++

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

Be First to Comment

Leave a Reply