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

๋ฐฑ์ค€ํ”„๋กœ๊ทธ๋ž˜๋ฐ for ๋ฌธ 1,2,3๋ฒˆ Swift

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

1.N์„ ์ž…๋ ฅ๋ฐ›์€ ๋’ค, ๊ตฌ๊ตฌ๋‹จ N๋‹จ์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

ํ•ต์‹ฌ : for ๋ฌธ ์“ธ ์ค„ ์•„๋‹ˆ?

import Foundation

let number = Int(readLine()!)!

for i in 1...9{
    print("\(number) * \(i) = \(number*i)")
}

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

์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ๊ฐ ์ค„์— A์™€ B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (0 < A, B < 10)

ํ•ต์‹ฌ: ์šฐ์„  ๋‘ ์ˆ˜๋ฅผ ๋”ํ•œ ๊ฑธ ๋ฐฐ์—ด์•ˆ์— ๋„ฃ๊ณ  ๊ทธ๊ฑธ ์ฐจ๋ก€ ์ฐจ๋ก€ ์ถœ๋ ฅํ•ด๋ด

import Foundation

let number = Int(readLine()!)!
var ab = [Int]()
for _ in 0..<number{
    let line = readLine()!
    let linearr = line.components(separatedBy: " ")
    let a = Int(linearr[0])!
    let b = Int(linearr[1])!
    ab.append(a+b)
}
for i in 0...ab.count-1{
  print(ab[i])
}

์•„๋ž˜๋ฅผ ์ฐธ๊ณ ํ•˜๋ฉด ๋” ์งง๊ฒŒ ์“ธ ์ˆ˜ ์žˆ์Œ

ํ•ต์‹ฌ: split ์“ธ ์ค„ ์•„๋‹ˆ? $0์“ธ ์ค„ ์•„๋‹ˆ? map์“ธ ์ค„ ์•„๋‹ˆ? reduce์“ธ ์ค„ ์•„๋‹ˆ?

๊ทธ๋ฆฌ๊ณ  ์ถœ๋ ฅ๊ฐ’์€ ํ•œ ๋ฐฉ์— ์•ˆ๋‚˜์™€๋„ ๋จ. ๋‚ด ์ •๋‹ต์—์„œ ๋ฐฐ์—ด์€ ๋นผ๋„ ๋์Œ

let a = Int(readLine()!)!
for _ in 1...a{
    let a = readLine()!
    let b = a.split{$0==" "}
    let c = b.map{Int($0)!}
    let d = c.reduce(0,+)
    print(d)
}

3.n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๋ถ€ํ„ฐ n๊นŒ์ง€ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

ํ•ต์‹ฌ: for๋ฌธ ์“ธ ์ค„ ์•„๋‹ˆ?

import Foundation

let number = Int(readLine()!)!
var a = 0
for i in 1...number{
   a = a+i
}
print(a)
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€