Palindrome number(leetcode)
Problem Statement
Given an integer x
, return true
if x
is a palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example,
121
is a palindrome while123
is not.
Examples:-
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
Follow up: Could you solve it without converting the integer to a string?
Approaches to Solve the Problem
My first approach is to convert the integer to a string then traverse the string in reverse and then match with it the given [without inbuilt function]
so let's convert it into a string by assigning a variable "text=x" After that decrement the string and put it into a "bag" variable so now we have the reverse of the string and now compare it with it a string.
if it equals print true else print false ;
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
let text="";
text=text+x;
let bag="";
for(let i=text.length-1; i>=0; i--)
{
bag=bag+text[i];
}
if(bag==text)
{
return true;
}
else{
return false;
}
};
Accepted | 236 ms | 51.2 MB | javascript |
2. The second approach , convert it into using an inbuilt function and then solve it
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
let text=x.toString()
let bag="";
for(let i=text.length-1; i>=0; i--)
{
bag=bag+text[i];
}
if(bag==text)
{
return true;
}
else{
return false;
}
};
Accepted | 338 ms | 51.1 MB | javascript |