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.
Ans :
var isPalindrome = function(number) {
if(number.toString() === number.toString().split("").reverse().join("")){
return true
}
return false;
};
How to optimize more and reduse time complexity
3
Answers
I am not sure which time complexity does the
reverse
function have (but I think it is O(n)).However, below it’s a function that does not use any string manipulation builtin but compares the digits starting from the indices in the middle of your number and then moves to the ones next to those, and so on, until it reaches the beginning/end of the number or it doesn’t find equal digits. It runs in O(n) (technically n/2 as worst case scenario when the number is palindrome).
The palindrome algo is quite easy, just iterate characters from the beginning and the end of a string and compare, convert your number to a string first:
And benchmark:
To reverse a number without (relative slow) string manipulation you can use a function that uses arithmetic for it: