[LeetCode/Kotlin]Easy - 9. Palindrome Number

2023. 6. 10. 15:51LeetCode/Kotlin | Easy

728x90
반응형
 

Palindrome Number - LeetCode

Can you solve this real interview question? Palindrome Number - 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. Ex

leetcode.com

문제

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?

풀이

나의 풀이법

풀이 접근 과정

그냥 간단한 팰린드롬 문제였다.

앞과 대칭되는 뒤에 문자를 비교해서 틀리면 false를 리턴시키면 된다.

최종 소스코드

class Solution {
    fun isPalindrome(x: Int): Boolean {
        val s = x.toString()
        val len = s.length
        for (i in 0 until len/2) {
            if (s[i] != s[len-i-1]) return false
        }
        return true
    }
}

 

728x90
반응형