Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example, 121 is a palindrome while 123 is not.
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
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.
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
var isPalindrome = function(x) {
let str = x.toString();
let answer = true;
for (let i = 0; i < str.length; i++) {
if (str[i] != str[(str.length)-i-1]) {
answer = false;
}
}
return answer
};
주어진 수의 자리수를 비교하기위해 문자열로 변환하여 인덱스를 활용하였다.
풀고나서 생각해보니 일일이 비교할 필요없이 뒤집어서 비교해도 된다는 것을 깨달았다.
var isPalindrome = function(x) {
let str = x.toString();
answer = str === str.split("").reverse().join("");
return answer;
};
코드는 더 간결해지긴 했지만 둘다 O(n)이라 그런지 runtime은 크게 차이나지 않았다.