관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - 다항식 더하기 (Kotlin) 본문

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

[Algorithm] 프로그래머스 - 다항식 더하기 (Kotlin)

참깨빵위에참깨빵_ 2023. 1. 13. 15:53
728x90
반응형
다항식을 계산할 때는 동류항끼리 계산해 정리한다. 덧셈으로 이뤄진 다항식 polynomial이 매개변수로 주어질 때, 동류항끼리 더한 결과값을 문자열로 리턴하는 solution()을 완성하라. 같은 식이면 가장 짧은 수식을 리턴한다

 

 

어떻게 풀어야 할지 감도 안 온 문제다. 인터넷의 다른 사람 풀이를 참고했다.

 

https://mycodingreview.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4%EB%8B%A4%ED%95%AD%EC%8B%9D%EB%8D%94%ED%95%98%EA%B8%B0

 

[프로그래머스/Java] Lv.0 다항식 더하기

문제 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public String solution(String polynomial) { String answer=""; String[] split=polynomial.split("\\s\\+\\s"); //매개변수로 들어온 다항

mycodingreview.tistory.com

class Solution {
    fun solution(polynomial: String): String {
        var answer = ""
        val split = polynomial.split("\\s\\+\\s".toRegex()).toTypedArray() //매개변수로 들어온 다항식을 전부 쪼깨서 배열에 넣음
        var con = 0
        var unk = 0
        for (i in split.indices) {
            if (split[i].matches("^[0-9]+$".toRegex())) {
                con += split[i].toInt()
            } else if (split[i] == "x") {
                unk += 1
            } else if (split[i].contains("x")) {
                unk += split[i].substring(0, split[i].length - 1).toInt()
            }
        }
        if (unk != 0 && con == 0) {
            answer = if (unk == 1) "x"
            else unk.toString() + "x"
        }
        if (unk == 0 && con != 0) {
            answer = con.toString()
        }
        if (unk != 0 && con != 0) {
            answer = if (unk == 1) "x + $con"
            else unk.toString() + "x" + " + " + con
        }
        return answer
    }
}

 

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

 

class Solution {
    fun solution(polynomial: String): String {
        var xCount = 0
        var num = 0

        for (s in polynomial.split(" ".toRegex())) {
            if (s.contains("x")) {
                xCount += if (s == "x") 1 else s.replace("x".toRegex(), "").toInt()
            } else if (s != "+") {
                num += s.toInt()
            }
        }
        return (if (xCount != 0) if (xCount > 1) "${xCount}x" else "x" else "") + if (num != 0) (if (xCount != 0) " + " else "") + num else if (xCount == 0) "0" else ""
    }
}

 

 

반응형
Comments