Algorithm

LeetCode - Palindrome Number

GREEN.1229 2022. 1. 7. 22:14

안녕하세요. 그린입니다🟢

이번 포스팅에서는 Palindrome Number 알고리즘을 풀어보려합니다.이 알고리즘은 간단한 문자열을 문자로 나누고 다루는 학습입니다.자꾸 조금 더 딥한 알고리즘 문제를 풀어야지 풀어야지... 하는데 매번 알고리즘은 어쩌다 생각날때마다 하고 있어서그래 오랜만이니까 쉬운거! 하면서 간단하고 찾아 자존감 획득하는 용도가 되고 있네요😭정말로! 다음 포스팅에서 학습할때는 딥한거 풀어볼께요 흙흙....🥲

그래서 오늘 풀어볼 문제는 LeetCode에서 Palindrome Number라는 문제입니다!

문제제시
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:

  • -231 <= x <= 231 - 1

문제풀이

class Solution {
    public func isPalindrome(_ x: Int) -> Bool {
      if x < 0 {
        return false
      }

      let inputStr = String(x)
      let reversedStr = String(inputStr.reversed())

      return inputStr == reversedStr
    }
}

그닥 따로 설명은 필요없을듯해요.

그래도 간단히 설명해보자면 해당 숫자를 문자열로 생각하고 거꾸로 순서를 다 뒤바꿔도 동일한 숫자인지 판별하는 문제입니다!

우선 음수 숫자가 들어오면 - 문자가 포함되기에 바로 false를 반환해줍니다.

거꾸로하면 무조건 다르기에..!

그리고 그게 아니라면 두개의 문자열을 만듭니다.

하나는 원래들어온 기존 숫자 두번째는 해당 문자열을 reverse한 문자!

이 두개의 비교값을 반환해주면 끝납니다🚀

 

마무리

진짜 그냥 자신감 획득 문제네요..ㅋㅋ

정말로 다음번 부터는 자신감 낮추는 딥한걸로 가져올께요 꼭!

[참고자료]

https://leetcode.com/problems/palindrome-number/

 

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