LeetCode #9 Palindrome Number

nathan·2022년 1월 12일
0

알고리즘문제

목록 보기
100/102

Palindrome Number


Link : 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 a palindrome while 123 is not.


Ex 1:

  • Input: x = 121
  • Output: true
  • Explanation: 121 reads as 121 from left to right and from right to left.

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

Ex 3:

  • Input: x = 10
  • Output: false
  • Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints

  • -2^31 <= x <= 2^31 - 1

Java code

class LC4 {
    public boolean isPalindrome(int x) {
        if(x < 0){
            return false;
        }

        String str = String.valueOf(x);
        int fullLength = str.length();
        int halfLength = str.length()/2;
        for(int i = 0; i < halfLength; i++){
            if (str.charAt(i) != str.charAt(fullLength-1-i)){
                return false;
            }
        }
        return true;
    }
}
//
//class Solution {
//    public boolean isPalindrome(int x) {
//        if(x<0){
//            return false;
//        }
//        else{
//            int tmp = x;
//            int res=0;
//            while(tmp>0){
//                int t = tmp%10;
//                res = res*10+t;
//                tmp = tmp/10;
//            }
//            return res==x;
//        }
//    }
//}

풀이

  • 팰린드롬은 파이썬으로도 푼 경험이 있었다.
  • 근데 항상 문자열로만 풀어와서 int형으로 풀어볼 생각조차 못했던 것 같다.
  • 우선 문자열 절반까지만 탐색하여 점점 가운데로 좁혀오게 인덱스를 이용하여 비교했다.
  • 주석처리가 된 부분은 문자열로 바꾸지 않고 푸는 코드인데 신기해서 가져왔다.
  • 10으로 계속해서 나눠주어 나머지 값을 쌓은 뒤 비교를 하는 기법이다.
  • 팰린드롬을 저렇게도 풀 수 있구나 감탄했다.

profile
나는 날마다 모든 면에서 점점 더 나아지고 있다.

0개의 댓글