Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
정수 배열 x가 주어질 때, 정수 x가 회문(역순으로 읽어도 같은 말이나 구절 또는 숫자)이면 true를 반환하라.
예를 들어, 121 회문이고, 123은 회문이 아니다.
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.
var isPalindrome = function(x) {
let arr = x.toString().split("").reverse().join("");
return x == arr ? true: false;
};
처음에 join
을 생각하지 못하고 엉뚱하게 reverse까지 하고 삽질을 하고있었다.
그리고 join()
으로 해주었는데 자꾸 wrong이 떠서 조인의 mdn을 확인해보니 join()
으로 할 경우에는 output이 "1,2,1"
로 출력이 되고 join("")
을 해야 "121"
로 출력이 된다!
var isPalindrome = function(x) {
const arr = String(x).split('');
while (arr.length > 1) {
if (arr.shift() !== arr.pop()) {
return false;
}
}
return true;
};
이 풀이는 정말 기가 막히다 ㅋㅋㅋ
자바스크립 배열 편을 공부하면 꼭 나오는 shift
와 pop
을 사용하여 풀다니 천재다!
shift()
메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다.
pop()
메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.
저 위 풀이는 arr의 첫 번째 요소와 arr의 마지막 요소가 같지 않다면 false를 반환하라 이 말이다.
이 풀이로 마무리하려다가 릿코드에 follow up을 보게 되었다.
Could you solve it without converting the integer to a string?
참눼 정수를 문자열로 변환하지 않고 문제를 풀 수 있냐는 말이다!!!!
var isPalindrome = function(x) {
if(x < 0) return false;
let reverse = 0;
for(let i = x; i >= 1; i = Math.floor(i/10))
// (1) i = 121 , 121 >= 1 이므로 아래문으로 내려간다
// (3) i = Math.floor(121 / 10) -> 121 나누기 10은 12.1이다.
// (3) Math.floor(12.1)을 하면 소수점은 제외하고 앞에 값들이 i가 된다. i = 12
// (5) i = Math.floor(12 / 10) -> 12 나누기 10은 1.2 이므로 소수점 제외하고 i = 1
reverse = reverse * 10 + i % 10;
// (2) reverse = 0 * 10 + 121 % 10 나머지 값은 1이다. -> reverse = 0 + 1 = 1
// (4) reverse = 1 * 10 + 12 % 10 나머지 값은 2이다. -> reverse = 10 + 2 = 12
// (6) reverse = 12 * 10 + 1 % 10 나머지 값은 1이다. -> reverse = 120 + 1 = 121
return reverse === x;
// reverse (121) === x (121) 이므로 true를 반환한다.
};
이해가 되지 않아 위에 영상을 보고 나니 참 천재들은 많구나.. 난 참 ㅈ밥이다라는 생각이 들었다
follow up을 제대로 읽어보고 문제를 풀자^^...