본문 바로가기
코딩테스트/리트코드LeetCode

[리트코드LeetCode][Easy][JAVA]9. Palindrome Number

by 빔o0O 2024. 9. 10.

 

문제

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.)

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

 

 


 

분석

  1. 앞으로 읽어도 뒤로 읽어도 숫자가 똑같은 경우를 palindrome  라고 하는 모양이다. 사람 이름으로 따지면 우영우? 다만, 음수인 경우 왼오를 바꿔서 읽으면 '-숫자'가 '숫자-'가 되므로 false.
  2. 주어진 수 x 가 이러한 수에 해당한다면 true를 반환하고 아니라면 false를 반환한다. 
  3. 앞뒤, 왼쪽 오른쪽이 같다, 즉 대칭이다, 라면 바로 떠오르는 건 후입선출 Stack.

 

 

 


 

피드백

  1. Stack을 떠올렸다고 기고만장해졌지만 효율의 극치인 코드를 보니 이런 자료구조같은 것도 필요 없이 기본 타입으로 해결하셨군... 알고리즘이 너무 미숙하다 정진하자. 
  2. 절반씩 쪼개서 할 것 없이 그냥 숫자를 뒤집은 값을 바로 구하고 그 값을 원래의 수와 비교하는 것이 빠르구나. 그렇구나... 
  3. 다양한 해결 방안이 있지만 Stack 같이 기고만장한 클래스를 사용한 사람은 드물군. 겸손하기. 

 

 

 


 

답안


class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0)	return false;	// 음수는 false
        if(x < 10)	return true;	// 일의 자리는 true
        
        Stack<Integer> xStack = new Stack<>();
        // 대칭구조에서 한 쪽의 개수를 구한다
        int digits = (x == 0) ? 1 : (int) (Math.log10(x) + 1);
        
        // 한쪽 면의 수를 stack으로 쌓기
        for(int i = 1; i <= digits / 2; i++) {
    		xStack.push(x % 10);
    		x /= 10;
        }
        
        // 자릿수가 홀수인 경우 가운데 수 제외
        if(digits % 2 != 0)	x /= 10;

        // 다른 쪽 수 검증 
        for(int i = 1; i <= digits / 2; i++) {
        	int tmpInt = xStack.pop();
        	if(x % 10 != tmpInt)	return false;
    		x /= 10;
        }
        
        return true;
    }
}

 

 

 


 

다른 사람의 답안

// 1. 가장 효율적인 코드
class Solution {
    public boolean isPalindrome(int x) {
        if(x<0){
            return false;
        }
        int originalnumber=x;
        int reversednumber=0;
        while(x!=0){
            int digit=x%10;
            reversednumber=reversednumber*10+digit;
            x/=10;}
            return reversednumber==originalnumber;
        }
           }

 

 

// 2. String으로 비교하기

class Solution {
    public boolean isPalindrome(int x) {
        String  num = "" + x;

        int i = 0 ; 
        int j = num.length()-1;

        while (i < j) {

           if ( num.charAt(i) != num.charAt(j)) {
            return false;
           } else {
            i++;
            j--;
           }

        }

        return true;
    }
}

 

 

 


 

🔗링크