forked from minsson/algorithm-study-in-swift
/
PGS_120863.swift
47 lines (42 loc) · 1.07 KB
/
PGS_120863.swift
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//
// PGS_120863.swift
// Seohyeon2
//
// Created by seohyeon park on 2022/12/18.
//
// https://school.programmers.co.kr/learn/courses/30/lessons/120863
import Foundation
func answer_PGS_다항식_더하기_120863() {
func solution(_ polynomial:String) -> String {
var num = 0
var xNum = 0
let str = polynomial.components(separatedBy: " + ")
str.filter {
$0.contains("x")
}.forEach {
if $0.count > 1 {
xNum += Int(Array($0.map {String($0)}[0..<$0.count-1]).joined())!
} else {
xNum += 1
}
}
str.filter {
!$0.contains("x")
}.forEach {
num += Int($0)!
}
if xNum == 0 {
return "\(num)"
} else if num == 0 {
if xNum == 1 {
return "x"
}
return "\(xNum)x"
} else {
if xNum == 1 {
return "x + \(num)"
}
return "\(xNum)x + \(num)"
}
}
}