[LeetCode] 3. Palindrome Number
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 palindrome while 123
is not.
Example 1:
Input: x = 121
Output: true
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.
Example 4:
Input: x = -101
Output: false
팔린드롬! 앞에서부터 봐도, 뒤에서부터 봐도 같은 값인지 확인하는 것
음수는 기호때문에 컷
가장 쉬운건 맨 앞의 문자와 맨뒤 문자 비교해가면서 확인하는것
class Solution {
public boolean isPalindrome(int x) {
String s = Integer.toString(x);
for(int i =0;i< s.length()/2;i++){
if(s.charAt(i) == s.charAt(s.length() -i -1)){
return true;
}
}
return false;
}
}
이렇게 했더니 x=121 일때 성공적으로 동작했음
but x가 한자리 수 일 때 정상적으로 작동하지 않음 이부분을 해결하기 위해
class Solution {
public boolean isPalindrome(int x) {
if(0 <= x && x<10) return true; // 0~9면 true
if(-10 < x && x<0) return false; // -9 ~ -1이면 false
String s = Integer.toString(x);
for(int i =0;i< s.length()/2;i++){
if(s.charAt(i) == s.charAt(s.length() -i -1)){
return true;
}
}
return false;
}
}
그래서 한자리 수 일 경우를 나눠줬는데
뜬금없이 x =123123일 때 true가 output으로 나온다
String s = "123123"일 경우에 for문 첫번째 동작일 때
charAt(0)은 1이고 charAt(5)는 3이라서 걸러질텐데...라고 생각하다가 이게 for문 돌면서 2에서 같아진다는걸 간과했다;
결국 for문 안에서 다르면 무조건 false로, 다 통과하면 true를 주기로 결정
class Solution {
public boolean isPalindrome(int x) {
if(0 <= x && x<10) return true; // 0~9면 true
if(-10 < x && x<0) return false; // -9 ~ -1이면 false
String s = Integer.toString(x);
for(int i =0;i< s.length()/2;i++){
if(s.charAt(i) != s.charAt(s.length() -i -1)){
return false;
}
}
return true;
}
}
이렇게 했더니
Success
Runtime: 7 ms, faster than 71.56% of Java online submissions for Palindrome Number.
Memory Usage: 38.5 MB, less than 57.06% of Java online submissions for Palindrome Number.
성공! 상위 30%정도의 속도가 나오지만 메모리 효율도 베스트는 아니다
이거 말고 다른 방법은 딱히 떠오르지 않아 베스트 답변을 뒤져보았음
class Solution {
public boolean isPalindrome(int x) {
int num = x;
if(num < 0 || (num % 10 ==0 && num != 0)){
return false;
}
int y =0;
while(num!=0){
int rem = num % 10;
num = num / 10;
y = y*10 + rem;
}
return x == y;
}
}
가장 빠른 결과값을 내는 코드이다
일단 한자리수 정수는 위에서 걸러주었고
이사람은 굳이 나처럼 String으로 변환해주지 않고 정수값 계산으로 비교를 진행했음
코드가 한번에 이해가 가지 않아 x가 121일 경우 while문 동작을 손코딩 해보았다
1. int rem = 121 % 10 ==> rem = 1
2. num = 121 / 10; ==> num = 12
3. y = 0 * 10 + 1 ==> y = 1
(두번째 try)
4. rem = 2
5. num = 1
6. y = 10 + 2; ==> y = 12
두번 째 try까지 하고 나서 코드의 목적이 보였다
숫자의 1의자리숫자를 맨앞으로 그리고 맨앞숫자를 맨뒤로 보내기 위한 알고리즘이다
기존의 x값을 쪼개서 y값에 하나하나 추가시켜주었던것!
내가 직전에 풀었던 Reverse Integer문제와 알고리즘 방식이 비슷하다
'skill > 알고리즘' 카테고리의 다른 글
삽입정렬(Insertion sort) Java 구현 (0) | 2021.03.03 |
---|---|
선택정렬(Selection sort) Java 구현 (0) | 2021.03.02 |
[LeetCode] 4. Remove Duplicates from Sorted Array (0) | 2021.02.26 |
[LeetCode] 2. Reverse Integer (0) | 2021.02.24 |
[LeetCode] 1. Two Sum (0) | 2021.02.23 |