LeetCode / easy / 9. Palindrome Number

lize·2024년 11월 26일
0

코딩테스트 연습

목록 보기
2/2

https://leetcode.com/problems/palindrome-number/description/

9. Palindrome Number

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

Examples

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

Follow up

Could you solve it without converting the integer to a string?


풀이

풀이1

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
  	if(x < 0) {
        return false;
    }

    if(x === 0) {
        return true;
    }
  
    const stringArr = String(x).split('');
    const reversedStringArr = stringArr.reverse();
    const reversedNumber = Number(reversedStringArr.join(''));
    return x === reversedNumber;
};

시간 복잡도

T(N) = O(logN)

풀이2

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    if(x < 0) {
        return false;
    }

    if(x === 0) {
        return true;
    }

    const digit = Math.floor(Math.log10(x)+1);
    let remainder = x;
	let reversedNumber = "";
  
    for(let i = digit - 1; i >= 0; i--) {
        reversedNumber = Math.floor(remainder / Math.pow(10, i)) + reversedNumber;
        remainder = remainder % Math.pow(10, i);
    }
  
  	return x + "" === reversedNumber;
};

Solution

https://leetcode.com/problems/palindrome-number/solutions/

0개의 댓글