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.
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?
var isPalindrome = function (x) {
// 숫자를 문자열로 바꿔서 선언한다
// 반복문을 문자열 길이의 반의 인덱스까지 돌린다
// 앞과 뒤의 인덱스의 문자열을 비교하면서 같으면 true, 다르면 false를 리턴한다
let string = String(x);
let half = Math.floor(string.length / 2);
for (let i = 0; i < half; i++) {
if (string[i] !== string[string.length - 1 - i]) {
return false;
}
}
return true;
};
❗️ 처음에는 음수도 -를 빼고 대칭적으로 이뤄졌을때 true를 리턴해야 한다고 이해를 해서 코드를 잘못 작성했다.
✏️ 굳이 문자열의 끝까지 반복문을 돌릴 필요가 없이 문자열 길이의 반까지만 돌려서 뒤의 문자열과 비교함으로써 소요시간을 줄였다.