관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - 영어가 싫어요 (Kotlin) 본문

알고리즘 문제 풀이/프로그래머스

[Algorithm] 프로그래머스 - 영어가 싫어요 (Kotlin)

참깨빵위에참깨빵_ 2023. 1. 4. 19:30
728x90
반응형
영어로 표기된 숫자를 수로 바꾸려고 한다. 문자열 numbers가 매개변수로 주어질 때, numbers를 정수로 바꿔 리턴하는 solution()을 완성하라

 

 

가장 먼저 떠오른 방법은 일일이 replace()로 바꿔주는 방법이었다.

 

class Solution {
    fun solution(numbers: String): Long {
        var a = numbers
        a = a.replace("zero", "0")
        a = a.replace("one", "1")
        a = a.replace("two", "2")
        a = a.replace("three", "3")
        a = a.replace("four", "4")
        a = a.replace("five", "5")
        a = a.replace("six", "6")
        a = a.replace("seven", "7")
        a = a.replace("eight", "8")
        a = a.replace("nine", "9")
        return a.toLong()
    }
}

 

그 다음은 문제 리스트 옆에 해시라는 글자가 있어서 Map을 써서도 풀어 봤다.

 

class Solution {
    fun solution(numbers: String): Long {
        val map = mapOf(
            "zero" to "0",
            "one" to "1",
            "two" to "2",
            "three" to "3",
            "four" to "4",
            "five" to "5",
            "six" to "6",
            "seven" to "7",
            "eight" to "8",
            "nine" to "9"
        )
        var result = numbers
        map.forEach { 
            result = result.replace(it.key, it.value)
        }
        
        return result.toLong()
    }
}

 

반응형
Comments