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
c++, java 를 풀면서도 팰린드롬 문제를 다양하게 풀어봤는데 대부분 문자열로 풀었었다.
근데 Swift는 문자열로 푸는게 더 어려울 것 같다는 생각을 했는데 마침 문제 아래에
Follow up: Could you solve it without converting the integer to a string?
String으로 바꾸지 않고 풀어보라는 내용이 있길래 한번 풀어보았다.
생각
단순하게 처음 숫자와 끝의 숫자를 비교해가면서 풀었다.
pow 함수를 사용했는데 그냥 10, Int 형태로 넣으면 pow가 Decimal 형태로 반환을 하는데 이는 Int로 변환이 안되나보다..
그래서 Float로 선언하고, 10.0 으로 Float 형태로 넣어서 Int로 변환해주었다.
다른 풀이
다른 사람의 풀이는 처음 숫자를 거꾸로 뒤집은 숫자를 구하여 그 숫자를 비교하였다.
pow 함수를 사용하지 않아서 더 깔끔한 것 같다.
Swift는 Int 형태로 구하는 것이 깔끔한 것 같다.
나의 코드
class Solution {
func isPalindrome(_ x: Int) -> Bool {
if x < 0 {
return false
}
let digit = Float(String(x).count)
var startIdx: Float = 0, endIdx: Float = digit - 1.0, startNum = 0, endNum = 0
while startIdx < endIdx {
startNum = (x / Int(pow(10.0, startIdx))) % 10
endNum = (x / Int(pow(10.0, endIdx))) % 10
if startNum == endNum {
startIdx += 1
endIdx -= 1
continue
} else {
return false
}
}
return true
}
}
다른 풀이
class Solution {
func isPalindrome(_ x: Int) -> Bool {
guard x >= 0 else { return false }
var xMutable = x
var reversed = 0
while xMutable != 0 {
let remainder = xMutable % 10
reversed = (reversed * 10) + remainder
xMutable = xMutable / 10
}
return x == reversed
}
}
'ALGORITHM' 카테고리의 다른 글
[Swift] LeetCode: Remove Duplicates from Sorted Array (inout) (0) | 2022.03.21 |
---|---|
[Swift] 9081 단어 맞추기 (next permutation) (0) | 2022.03.19 |
[Swift] LeetCode: Two Sum (0) | 2022.03.12 |
[Swift] 14889 스타트와 링크 (조합) (0) | 2022.03.11 |
[Swift] Lv2.위장 (Dictionary) (0) | 2022.03.09 |