[LeetCode][Java] Palindrome Number

최지수·2021년 10월 3일
0

Algorithm

목록 보기
14/77
post-thumbnail

문제

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.

제한사항

  • 231x2311-2^{31} \leq x \leq 2^{31} - 1
  • Could you solve it without converting the integer to a string?

접근

팔린드롬Palindrome여부를 확인하는 문제입니다. 가장 단순한 방법은 정수를 문자열로 변환해서 끝단끼리 비교해가는 방법도 있겠지만, 이번 문제에서는 문자 형변환을 하지 않고 구할 수 있는가?라는 전제를 달았어요.

저는 주어진 숫자를 역전시키는 방식으로 팔린드롬 여부를 구했어요. 주어진 숫자가 0이 될때까지 아래의 식을 적용하면 숫자를 역전시킬 수 있어요. 물론 구하고 난 다음에 비교를 위해 임시 변수에 저장해야 합니다.

rev=(rev×10)+xmod10rev = (rev \times 10) + x \bmod 10

답안

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

        int tmpX = x, reverseX = 0;
        while(tmpX > 0){
            reverseX = (reverseX * 10) + (tmpX % 10);
            tmpX /= 10;
        }
        return reverseX == x;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글