๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution

[Swift] Baekjoon ํฐ ์ˆ˜ A + B 10757๋ฒˆ

by Fomagran ๐Ÿ’ป 2022. 1. 6.
728x90
๋ฐ˜์‘ํ˜•

Problem

 

 

10757๋ฒˆ: ํฐ ์ˆ˜ A+B

๋‘ ์ •์ˆ˜ A์™€ B๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ๋‹ค์Œ, A+B๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net


Solution

 

1. ๋ฌธ์ž๋ฅผ ์ž…๋ ฅ๋ฐ›๊ณ  ๊ณต๋ฐฑ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค.

 

let line = readLine() ?? ""
let lineArr = line.split(separator: " ").map{String($0)}

 

2. ๋‘ ๋ฌธ์ž๋ฅผ Array๋กœ ๋งŒ๋“ค๊ณ  ๋’ค์ง‘์–ด์ค€๋‹ค.

 

var A = Array(lineArr[0].map{String($0)}.reversed())
var B = Array(lineArr[1].map{String($0)}.reversed())

 

3. ๋” ๊ธด ๋ฌธ์ž๊ฐ€ ์žˆ๋‹ค๋ฉด ๋’ค์— ์ฐจ์ด๋งŒํผ 0์„ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

 

var isALong = A.count > B.count
let addZero = Array(repeating: "0", count: abs(A.count-B.count))

A = isALong ? A : A + addZero
B = isALong ? B + addZero : B

 

4. for๋ฌธ์œผ๋กœ ๋์—์„œ๋ถ€ํ„ฐ ๋‘ ์ˆซ์ž๋ฅผ ๋”ํ•ด์ค€๋‹ค.

 

๋งŒ์•ฝ ๋”ํ•œ ์ˆซ์ž๊ฐ€ 10์„ ๋„˜๋Š”๋‹ค๋ฉด one์— ์ €์žฅํ•˜์—ฌ ๋‹ค์Œ ์ˆซ์ž๋ฅผ ๋”ํ•  ๋•Œ ๋”ํ•ด์ค๋‹ˆ๋‹ค.

 

๊ทธ๋ฆฌ๊ณ  ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ์ˆซ์ž๋Š” 10์œผ๋กœ ๋‚˜๋ˆˆ ๊ฒƒ์ด ์•„๋‹Œ ๊ทธ๋Œ€๋กœ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

 

var one = 0
var answer:[String] = []
let count = isALong ? A.count : B.count

for i in 0..<count {
    let sum = Int(A[i])! + Int(B[i])! + one
    one = sum/10
    if i == count - 1 {
        answer.append(String(sum))
    }else {
        answer.append(String(sum%10))
    }
}

 

5. ์ •๋‹ต์„ ๋’ค์ง‘๊ณ  ๋ฌธ์ž๋กœ ๋งŒ๋“ค์–ด ์ถœ๋ ฅํ•œ๋‹ค.

 

print(Array(answer.reversed()).joined())

Source Code

 


P.S

 

์˜ค๋žœ๋งŒ์— ๋ฐฑ์ค€ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

 

'๊ฐ€๋ณ๊ฒŒ ๋ธŒ๋ก ์ฆˆ 5๋‚˜ ํ’€์–ด๋ณผ๊นŒ?' ๋ผ๋Š” ๋งˆ์ธ๋“œ๋กœ ํ’€์—ˆ๋Š”๋ฐ ์™€... ์ƒ๊ฐ๋ณด๋‹ค ์–ด๋ ค์› ๋‹ค...

 

๋ญ”๊ฐ€ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฌธ์ œ๊ฐ€ ์›ํ•˜๋Š” ๊ฒƒ๊ณผ ๋ฐฑ์ค€์ด ์›ํ•˜๋Š” ๊ฒƒ์ด ์ข€ ๋‹ค๋ฅธ ๊ฒƒ ๊ฐ™๋‹ค...

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€