[LeetCode]9. Palindrome Number - JavaScript

롱롱·2022년 8월 10일
0

LeetCode 문제풀이

목록 보기
2/5

LeetCode에서 풀어보기

👀 Problem

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.

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

✔ Solution

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은 크게 차이나지 않았다.

profile
개발자를 꿈꾸며 공부중입니다.

0개의 댓글