Question and Examples
Given an integer x, return true if x is a palindrome
, and false otherwise.
An integer is a palindrome when it reads the same forward and backward.
// Example
isPalindrome(123) // false
isPalindrome(12321) // true
isPalindrome(0) // true
I had difficulties trying to solve this question WITHOUT inverting the integer to a string. So this was my solution:
My Solution
function isPalindrome(x) {
// invert int to string
const num = x.toString()
// implement pointer method
let pointer1 = 0
let pointer2 = num.length - 1
// when the length of the string is a even number
// OR
// when the length of the string is a odd number
if (num.length % 2 === 0) {
// seting a condition to prevent infinite loop
while (pointer1 < pointer2) {
let sum = num[pointer1] - num[pointer2]
// if the integer is a palindrome, the two numbers
// at the respective ends should return 0
// when subtracted
if (sum !== 0) {
return false
}
// if it does return 0 when subtracted,
// increment and decrement each respective pointers
pointer1 = pointer1 + 1
pointer2 = pointer2 - 1
}
} else {
// same logic for when the length of the string
// is a odd number
while (pointer1 < pointer2 || pointer1 === pointer2) {
let sum = num[pointer1] - num[pointer2]
if (sum !== 0) {
return false
}
pointer1 = pointer1 + 1
pointer2 = pointer2 - 1
}
}
// if all tests pass without returning false,
// return true
return true
}
Time Complexity: O(n)
Implementing the pointers method really helped out to achieve the time complexity of O(n)
.