[LeetCode] 9. Palindrome Number (Java)

2023. 1. 4. 07:00알고리즘/LeetCode

Description

Given an integer x, return true if x is a palindrome, and false otherwise.

 

주어진 정수 x가 거꾸로 읽어도 같다면 true 아니면 false를 반환하기.

 

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?

 

Solution

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0){
            return false;
        }
    
        List<Integer> set = new ArrayList<>();

        while(x!=0){
            set.add(x%10);
            x/=10;
        }
        for(int i=0;i<set.size()+1/2;i++){
            if(set.get(i)!=set.get(set.size()-i-1)){
                return false;
            }
        }
        return true;
    }
}

음수인 경우에 무조건 회문이 아니기 때문에 false를 반환하고 set에 각 자리 수를 넣은 뒤에 맨 앞과 맨 뒤에서 부터 비교해 주었다.