[LV.1] 숫자 문자열과 영단어

Heedon Ham·2023년 4월 21일
0
post-thumbnail

숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어집니다. s가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성해주세요.

다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.
1478 → "one4seveneight"
234567 → "23four5six7"
10203 → "1zerotwozero3"

제한사항
1 ≤ s의 길이 ≤ 50
s가 "zero" 또는 "0"으로 시작하는 경우는 주어지지 않습니다.
return 값이 1 이상 2,000,000,000 이하의 정수가 되는 올바른 입력만 s로 주어집니다.

sresult
"one4seveneight"1478
"23four5six7"234567
"2three45sixseven"234567
"123"123

오답 풀이

String 타입의 input이 들어오므로, Array로 치환한 뒤, 각 index의 element가 숫자이면 Int로 변환, 아닐 경우, text를 Int로 변환할 케이스를 구분해서 각 text만큼의 길이만큼 index를 넘어가도록 했다.

import Foundation

func solution(_ s:String) -> Int {
    var result = 0
    var i = 0
    var array = Array(s) 
    while i < array.count {
        result *= 10
        if let num = Int(String(array[i])) {
            result += num
            i += 1
        } else {
            switch array[i] {
                case "z":
                    i += 4
                case "o":
                    result += 1
                    i += 3
                case "e":
                    result += 8
                    i += 5
                case "n":
                    result += 9
                    i += 4
                case "t":
                    if array[i+1] == "w" {
                        result += 2
                        i += 3
                    } else {
                        result += 3
                        i += 5
                    }
                case "f":
                    if array[i+1] == "o" {
                        result += 4
                    } else {
                        result += 5
                    }
                    i += 4
                default:
                    break
            }
        }
    }
    
    return result
}

실행 결과
signal: illegal instruction (core dumped)
테스트 결과 (~˘▾˘)~: 4개 중 1개 성공

while문을 돌면서 오버플로우로 에러가 나타나는 듯 보인다.


모범 답안

String에서 특정 문자열을 변환해주는 replacingOccurences() 메서드를 활용하면 간단하게 해결할 수 있다.
즉, 0~9에 해당하는 text들을 해당 정수로 변환하면 된다.

replacingOccurrences(of:with:)
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

import Foundation

func solution(_ s:String) -> Int {
	var result = s
    let text = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    
    for i in 0..<text.count {
    	result = result.replacingOccurrences(of: text[i], with: String(i))
    }
    
    return Int(result)!
}
profile
dev( iOS, React)

0개의 댓글