FrontEnd :-)

[LeetCode-JS] Palindrome Number 본문

JavaScript/Algorithm

[LeetCode-JS] Palindrome Number

code10 2022. 12. 7. 00:06

🙋 문제: Palindrome Number (대칭수)

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.

 

🅰️ 풀이:

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    const arr = x.toString().split("");
    for(let i = 0; i < arr.length; i++){
        if(arr[i] !== arr[arr.length -(i+1)]){
            return false;
        }
    }
    return true;
};

 

다른 사람 풀이:

  var s = '' + x; //숫자 => 문자열
  var l = 0;
  var r = s.length - 1;
  while (l < r) {
    if (s[l] !== s[r]) return false;
    l++;
    r--;
  }
  return true;

>> while 루프는 이상하게 잘 안 써진다. 

x = "" + x
return x === x.split("").reverse().join("");

>> reverse, join 방법도 생각하긴 했었다.

'JavaScript > Algorithm' 카테고리의 다른 글

[LeetCode-JS] Merge Two Sorted Lists  (0) 2022.12.15
[LeetCode-JS] Valid Parentheses  (0) 2022.12.10
[LeetCode-JS] Longest Common Prefix  (0) 2022.12.09
[LeetCode-JS] Roman to Integer  (0) 2022.12.08
[LeetCode-JS] Two Sum  (0) 2022.12.05
Comments