coding test/leetCode

[leetCode/JS] 9. Palindrome Number

쭘봉 2022. 11. 23. 16:55

문제 설명

Given an integer x, return true if x is a palindrome, and false otherwise.

palindrome : An integer is a palindrome when it reads the same forward and backward. 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

내 솔루션

  • 앞뒤로 하나씩 비교하기 때문에 중간에 다르면 멈출 수 있다는 장점이 있다.
  • 런타임이 빠른편.
var isPalindrome = function(x) {
  const str = String(x).split('');
  let awnser = true;
  for(let i = 0; i < str.length/2; i++) {
    if(str[i] !== str[str.length - i - 1]) {
      awnser = false;
      break;
    }
  }
  return awnser;
};

최고의 솔루션

  • String, Array 로 바꾸지 않고 number에서 변환해서 비교한 솔루션이다.
  • 런타임은 나보다 느리지만 메모리를 적게 쓴다.
var isPalindrome = function(x) {
    var reverse = 0;
    var copy = x;

    while (copy > 0) {
      const digit = copy % 10;
      reverse = reverse * 10 + digit;
      copy = Math.floor(copy / 10);
    }
    return reverse == x;
};

감상평

  • 숫자 상태에서 뒤집는 방법을 고민했는데 좋은 공부가 되었다.