Coder's Cat

## LeetCode: Palindrome Number

2019-10-21

LeetCode: Palindrome number, explanation and solution with C++/Java/Python

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

## LeetCode Problem

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

Example:

## Explanation

This problem is easy, according to problem description:

If $input < 0$, it must not be palindrome number.

If $input < 10$, it’s length is 1, and it must be a palindrome number.

Otherwise, we reverse the number by digits, and check whether equal with origin number.

Note the edge case of integer overflow when reversing a number:

We need to avoid this in the loop.

An alternative solution is converting an integer into string, then check str with reverse(str).

## Python

In Python, str(x) will convert x into string, with extended slice index, s[start:stop:step] can be used for fetch substring of a string.

And s[::-1] reverse string using slicing, -1 denotes starting from end and stop at the start, hence reversing string.

Preparing for an interview? Check out this!

Join my Email List for more insights, It's Free!😋