티스토리 뷰
try-catch 문을 사용하여 int형으로 변환이 가능하지 않을 때 아스키코드 처리를 해주는 코드를 작성하였다.
import Foundation
let input = readLine()!.split(separator: " ")
let n = input.first!.description
let b = Int(input.last!.description)!
let lengthOfN = n.count
var result = 0
for i in (0..<lengthOfN).reversed() {
let power = Int(pow(Double(b), Double(lengthOfN - i - 1)))
let element = n[n.index(n.startIndex, offsetBy: i)].description
if let number = Int(element) {
result += number * power
} else {
let number = Int(String((element.unicodeScalars.first?.value)!))! - 55
result += number * power
}
}
print(result)
하지만 매번 pow 함수로 base의 거듭제곱을 해주는 것은 비효율적이다.
for문을 돌 때마다 base를 곱해주면 조금 더 시간 복잡도를 줄일 수 있을 것이다.
Java의 경우 4ms(80->76), Swift의 경우는..그대로다..
'Algorithm > Baekjoon Online Judge' 카테고리의 다른 글
1212번 '8진수 2진수' (0) | 2018.07.31 |
---|---|
1373번 '2진법 8진법' (0) | 2018.07.31 |
11005번 '진법 변환 2' (0) | 2018.07.31 |
9613번 'GCD 합' (0) | 2018.07.31 |
1934번 '최소공배수' (0) | 2018.07.31 |