본문 바로가기
Algorithm & SQL/LeetCode

LeetCode 9.Palindrome Number (Easy) - Kotlin

by YoonJong 2025. 3. 2.
728x90

문제

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

 

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?

 

해결

class Solution {
    fun isPalindrome(x: Int): Boolean {
        if (x < 0) {
            return false
        }

        val str = x.toString()  // Int 형은 length 사용불가 

        var left = 0
        var right = str.length-1

        while(left < right) {   // 교차할때까지 반복
            if (str[left] != str[right]) {
                return false
            }
            left ++
            right --   
        }

        return true
    }
}
728x90

'Algorithm & SQL > LeetCode' 카테고리의 다른 글

LeetCode 13. Roman to Integer (Easy) - Kotlin  (0) 2025.03.13
LeetCode 1.Two Sum (Easy) - Kotlin  (0) 2025.02.28

댓글