250x250
반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
관리 메뉴

수니의 개발새발

[LeetCode/Swift] 9. Palindrome Number 본문

Algorithm

[LeetCode/Swift] 9. Palindrome Number

개발자 수니 2024. 1. 22. 20:09
728x90
반응형

💡 문제 (Easy)

 

LeetCode - The World's Leading Online Programming Learning Platform

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

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

정수 x가 주어졌을 때, x가 palindrome(앞에서 뒤로, 뒤에서 앞으로 읽었을 때 동일한 내용이 되는 것)인 경우 true를 반환하고 그렇지 않은 경우 false를 반환합니다.

 

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

👩🏻‍💻 해결

1차 정수 X를 while문으로 뒤집어 비교

class Solution {
    func isPalindrome(_ x: Int) -> Bool {
        if x >= 0 {
            var result = 0
            var copyX = x
            while copyX != 0 {
                result *= 10
                result += copyX % 10
                copyX /= 10
            }
            return result == x
        } else {
            return false
        }
    }
}

 

2차 String으로 변환하여 해결

class Solution {
    func isPalindrome(_ x: Int) -> Bool {
        return String(x) == String(String(x).reversed())      
    }
}
728x90
반응형
Comments