Write a program to determine whether a given number is a palindrome. A palindromic number is a number that remains the same when its digits are reversed. Like 16461, for example, is “symmetrical”.

We know that even if we reverse a palindrome number, its value will not change. This fact forms the idea behind proposed solutions. If the given number is equal to its reverse, it is a palindrome; otherwise, it’s not a palindrome number.

Practice this problem

Iterative Version

The iterative implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

Palindrome

Java


Download  Run Code

Output:

Palindrome

Python


Download  Run Code

Output:

Palindrome

The time complexity of the above solution is O(log(n)) and doesn’t require any extra space.

Recursive Version

The algorithm can be implemented recursively as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Palindrome

Java


Download  Run Code

Output:

Palindrome

Python


Download  Run Code

Output:

Palindrome

The time complexity of the above solution is O(log(n)) and requires O(log(n)) implicit space for the call stack.

 
We can also easily merge reverse() and isPalindrome() functions into one. The following C++ program demonstrates it:

C++


Download  Run Code

Please note that the use of static variables is not recommended. Instead, pass the variables as an argument to the isPalindrome() function.