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 방법도 생각하긴 했었다.