관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - 숨어있는 숫자의 덧셈 (2) (Kotlin) 본문

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

[Algorithm] 프로그래머스 - 숨어있는 숫자의 덧셈 (2) (Kotlin)

참깨빵위에참깨빵_ 2023. 1. 13. 15:58
728x90
반응형
문자열이 매개변수로 주어진다. 문자열은 소문자, 대문자, 자연수로만 구성돼 있다. 문자열 안의 자연수들의 합을 리턴하는 solution()을 완성하라

 

 

이 문제도 어떻게 풀어야 할지 감도 안 와서 인터넷을 참고했다.

 

https://mycodingreview.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4%EC%88%A8%EC%96%B4%EC%9E%88%EB%8A%94%EC%88%AB%EC%9E%90%EC%9D%98%EB%8D%A7%EC%85%882

 

[프로그래머스/Java] Lv.0 숨어있는 숫자의 덧셈 (2)

문제 풀이 1 2 3 4 5 6 7 8 9 10 11 12 class Solution { public int solution(String my_string) { int answer = 0; //모든 숫자를 더할 변수 String[] split=my_string.split("[a-zA-z]+"); //매개변수로 들어온 문자열을 대소문자 알파벳

mycodingreview.tistory.com

class Solution {
    fun solution(my_string: String): Int {
        var answer = 0
        val split = my_string.split("[a-zA-z]+".toRegex()).toTypedArray()
        for (i in split.indices) {
            if (split[i].matches("[0-9]+".toRegex())) {
                answer += split[i].toInt()
            }
        }
        return answer
    }
}

 

간단하게 줄이면 아래처럼 된다.

 

class Solution {
    fun solution(my_string: String): Int  = 
    my_string.split("[A-z]+".toRegex())
        .filter(String::isNotEmpty)
        .sumOf(String::toInt)
}

 

반응형
Comments