AlgoMaster Logo

Palindrome Number

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Convert Number to String

Intuition:

The simplest way to determine if a number is a palindrome is to convert it to a string and check if the string reads the same forwards and backwards.

  1. Convert the integer to a string.
  2. Compare the original string with its reverse. If they are the same, then the number is a palindrome.

Code:

2. Reversing Digits Approach

Intuition:

Instead of converting the integer to a string, we can reverse the digits of the integer itself and compare it with the original integer.

  1. Handle edge cases for negative numbers and single-digit numbers.
  2. Reverse the digits of the number.
  3. Compare the reversed number with the original number.

Code:

Complexity Analysis:

  • Time Complexity: O(n), where n is the number of digits in the number.
  • Space Complexity: O(1), since we're only using a few integers for temporary storage.

3. Reversing Half of the Number

Intuition:

We can improve upon the previous approach by only reversing half of the number and checking if the first half equals the reversed second half. This reduces the amount of work needed, particularly for very long numbers.

  1. A number is a palindrome if dividing and reversing its first half equals the second half.
  2. Reverse the second half of the number and compare it with the first half.

Code: