본문 바로가기
LeetCode

[LeetCode] 9. Palindrome Number

by JungSeung 2023. 10. 17.
728x90

https://leetcode.com/

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

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:

  • -2^31 <= x <= 2^31 - 1

 

Code :

var isPalindrome = function(x) {
    // 정수의 범위를 나타내는 상수 값
    const MinNum = -2147483648; // -2^31 값
    const MaxNum = 2147483647;  // 2^31-1 값
    // 주어진 정수가 범위를 벗어나면 회문이 아님
    if (x < MinNum || x > MaxNum) {
        return false;
    }
    // 정수를 문자열로 변환하고, 뒤집어서 다시 정수로 변환
    const reverse =  x.toString().split("").reverse().join("");
    // 원래의 정수와 뒤집은 정수가 같으면 회문
    return x === Number(reverse);
};

 

Solutions Code :

// Solution 1
var isPalindrome = function(x) {
    // 정수를 문자열로 변환
    var s = x.toString();
    // 문자열을 뒤집어서 새로운 문자열 생성
    var t = s.split("").reverse().join("");
    // 원래의 문자열과 뒤집은 문자열이 같으면 회문
    return s === t;
};

// Solution 2
var isPalindrome = function(x) {
    // 음수 또는 10의 배수인 경우 회문이 아님
    if (x < 0 || (x !== 0 && x % 10 === 0)) {
        return false;
    }
    var half = 0;  // 숫자의 뒷부분을 저장할 변수 초기화
    // 주어진 숫자를 반으로 나누어 뒤집은 뒷부분 생성
    while (x > half) {
        half = half * 10 + x % 10;
        x = Math.floor(x / 10);
    }
    // 홀수 자릿수를 가진 경우 중앙값은 무시하여 비교
    return x === half || x === Math.floor(half / 10);
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 11. Container With Most Water  (0) 2023.10.18
[LeetCode] 10. Regular Expression Matching  (0) 2023.10.18
[LeetCode] 8. String to Integer (atoi)  (2) 2023.10.16
[LeetCode] 7. Reverse Integer  (0) 2023.10.16
[LeetCode] 6. Zigzag Conversion  (0) 2023.10.13