Intuition
The initial thought to solve this problem is to convert the integer into a string. This allows us to leverage string manipulation functions to easily reverse the string and compare it to the original. By comparing the original and reversed strings, we can determine if the number is a palindrome.
Approach
- Convert to String: The integer is converted to a string using the
strval()
function in PHP. - Reverse String: The string is reversed using the
strrev()
function. - Compare Strings: The original string and the reversed string are compared. If they are equal, the number is a palindrome; otherwise, it’s not.
Complexity
- Time complexity: O(log n)
- Converting an integer to a string and reversing a string typically takes logarithmic time in terms of the number of digits in the integer.
- Space complexity: O(log n)
- The space required to store the string representation of the integer is proportional to the number of digits, which is logarithmic in terms of the integer’s value.
Problem
Given an integer x
, return true
if x
is a
palindrome, and false
otherwise.
Example 1:
Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -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: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Code
class Solution {
function isPalindrome($x) {
return strval($x) === strrev(strval($x));
}
}
Explanation:
- The
isPalindrome
function takes an integerx
as input. - It converts
x
to a string usingstrval()
and then reverses the string usingstrrev()
. - The original string and the reversed string are directly compared using the strict equality operator (
===
). If they are equal, the function returnstrue
; otherwise, it returnsfalse
.
Note:
This solution provides a simple and intuitive approach to solving the palindrome number problem. However, it’s worth noting that converting the integer to a string might introduce unnecessary overhead for large integers. In some cases, a mathematical approach that avoids string manipulation might be more efficient.
Alternative Approach (without string conversion):
A more efficient approach would involve reversing the integer digit by digit without converting it to a string. This can be achieved by repeatedly extracting the last digit and constructing a new reversed integer. However, this approach requires more careful handling of edge cases and might be slightly more complex to implement.