본문으로 바로가기

Description

주어진 int값이 거꾸로 시작해도 일치하는 값일 경우 true, 아니면 false를 반환합니다.

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.

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:

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

Follow up:

Could you solve it without converting the integer to a string?

Solution 1. String 변환

public boolean isPalindrome(int x) {
        
    // return negative int
    if(x < 0){
        return false;
    }
    
    // convert int to String
    String intStr = Integer.valueOf(x).toString();
    
    int len = intStr.length();
    for(int i=0; i< len/2; i++){
        if(intStr.charAt(i) != intStr.charAt(intStr.length()-1-i)){
            return false;
        }
    }
    return true;
}

주어진 int값을 String으로 변환한뒤 앞뒤 값을 비교해 나갑니다.

Reference

 

Palindrome Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com