난이도: EASY
문제
Given an integer x, return true if x is a palindrome, and false otherwise.
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
class Solution {
public boolean isPalindrome(int x) {
String xStr = String.valueOf(x);
char[] pd = xStr.toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = pd.length - 1 ; i = 0; i++) {
sb.append(pd[i]);
}
return xStr.equals(sb.toString()) ? true : false;
}
}
시도1이라고 썼지만 오타가 몇 개 있어서 시도n쯤 ㅋㅋㅋㅋ...
암튼 오타 고친 뒤 시도1.
근 데 첨 풀 때는 몰랐는데 for문 조건문을 잘 못 씀.
for (초기화; 조건식; 증감식) {
// 반복 실행될 코드
}
조건식이 [~하는 동안] 인데, [~까지] 로 순간 착각함... 11월 초 이후로 지금까지 자바를 너무 오래쉬었네.....
그래서 암튼 수정하고 수정하는 김에 증감식도 ++ 아니고 --로 변경.
나의 최종 제출 답안:
class Solution {
public boolean isPalindrome(int x) {
String xStr = String.valueOf(x);
char[] pd = xStr.toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = pd.length - 1 ; i >= 0; i--) {
sb.append(pd[i]);
}
return xStr.equals(sb.toString()) ? true : false;
}
}
chatGPT에게 더 간단하고 효율적이게 수정해달라고 요청한 답안:
1. Two Pointers 방법 (String)
class Solution {
public boolean isPalindrome(int x) {
String xStr = String.valueOf(x);
int left = 0;
int right = xStr.length() - 1;
while (left < right) {
if (xStr.charAt(left) != xStr.charAt(right)) {
return false; // 팰린드롬이 아님
}
left++;
right--;
}
return true; // 팰린드롬
}
}
2. String 변환없이 하는 방법(추천)
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false; // 음수 및 10의 배수 예외 처리
int reversed = 0;
int original = x;
while (x > 0) {
reversed = reversed * 10 + x % 10; // 뒤집기
x /= 10;
}
return original == reversed; // 원래 숫자와 뒤집은 숫자가 같은지 비교
}
}
'Coding Challenges > LeetCode' 카테고리의 다른 글
[SQL50] 1757. Recyclable and Low Fat Products (0) | 2025.02.06 |
---|---|
[Java] 20. Valid Parentheses (0) | 2025.02.06 |
[Java] 14. Longest Common Prefix (2) | 2025.02.05 |
[Java] 13. Roman to Integer (0) | 2025.02.04 |
[Java] 1. Two sum (3) | 2025.02.03 |