Notice
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 서비스 쓰레드 차이
- Rxjava Observable
- jvm이란
- 클래스
- rxjava hot observable
- 자바 다형성
- 안드로이드 유닛테스트란
- 안드로이드 레트로핏 crud
- 큐 자바 코드
- ar vr 차이
- android retrofit login
- 멤버변수
- 스택 큐 차이
- 안드로이드 유닛 테스트 예시
- rxjava disposable
- 플러터 설치 2022
- ANR이란
- 안드로이드 레트로핏 사용법
- 안드로이드 os 구조
- 스택 자바 코드
- 안드로이드 유닛 테스트
- 객체
- 안드로이드 라이선스 종류
- android ar 개발
- 2022 플러터 안드로이드 스튜디오
- 안드로이드 라이선스
- rxjava cold observable
- jvm 작동 원리
- 2022 플러터 설치
- 서비스 vs 쓰레드
Archives
- Today
- Total
나만을 위한 블로그
[Algorithm] 프로그래머스 - 다항식 더하기 (Kotlin) 본문
728x90
반응형
다항식을 계산할 때는 동류항끼리 계산해 정리한다. 덧셈으로 이뤄진 다항식 polynomial이 매개변수로 주어질 때, 동류항끼리 더한 결과값을 문자열로 리턴하는 solution()을 완성하라. 같은 식이면 가장 짧은 수식을 리턴한다
어떻게 풀어야 할지 감도 안 온 문제다. 인터넷의 다른 사람 풀이를 참고했다.
[프로그래머스/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 ""
}
}
반응형
'알고리즘 문제 풀이 > 프로그래머스' 카테고리의 다른 글
[Algorithm] 프로그래머스 - 안전지대 (Kotlin) (0) | 2023.01.13 |
---|---|
[Algorithm] 프로그래머스 - 숨어있는 숫자의 덧셈 (2) (Kotlin) (0) | 2023.01.13 |
[Algorithm] 프로그래머스 - 최댓값 만들기 (2) (Kotlin) (0) | 2023.01.13 |
[Algorithm] 프로그래머스 - 캐릭터의 좌표 (Kotlin) (0) | 2023.01.13 |
[Algorithm] 프로그래머스 - 직사각형 넓이 구하기 (Kotlin) (0) | 2023.01.11 |
Comments