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

๋ฐฑ์ค€ ํ”„๋กœ๊ทธ๋ž˜๋ฐ for๋ฌธ 4,5,6,7๋ฒˆ Swift

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

4.๋ณธ๊ฒฉ์ ์œผ๋กœ for๋ฌธ ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์ „์— ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์ด ์žˆ๋‹ค. ์ž…์ถœ๋ ฅ ๋ฐฉ์‹์ด ๋Š๋ฆฌ๋ฉด ์—ฌ๋Ÿฌ ์ค„์„ ์ž…๋ ฅ๋ฐ›๊ฑฐ๋‚˜ ์ถœ๋ ฅํ•  ๋•Œ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด๋‹ค.

C++์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๊ณ  cin/cout์„ ์‚ฌ์šฉํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด, cin.tie(NULL)๊ณผ sync_with_stdio(false)๋ฅผ ๋‘˜ ๋‹ค ์ ์šฉํ•ด ์ฃผ๊ณ , endl ๋Œ€์‹  ๊ฐœํ–‰๋ฌธ์ž(\n)๋ฅผ ์“ฐ์ž. ๋‹จ, ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋” ์ด์ƒ scanf/printf/puts/getchar/putchar ๋“ฑ C์˜ ์ž…์ถœ๋ ฅ ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ ๋œ๋‹ค.

Java๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋‹ค๋ฉด, Scanner์™€ System.out.println ๋Œ€์‹  BufferedReader์™€ BufferedWriter๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. BufferedWriter.flush๋Š” ๋งจ ๋งˆ์ง€๋ง‰์— ํ•œ ๋ฒˆ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค.

Python์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋‹ค๋ฉด, input ๋Œ€์‹  sys.stdin.readline์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๋‹จ, ์ด๋•Œ๋Š” ๋งจ ๋์˜ ๊ฐœํ–‰๋ฌธ์ž๊นŒ์ง€ ๊ฐ™์ด ์ž…๋ ฅ๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ž์—ด์„ ์ €์žฅํ•˜๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ .rstrip()์„ ์ถ”๊ฐ€๋กœ ํ•ด ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

๋˜ํ•œ ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ์€ ๋ณ„๊ฐœ์ด๋ฏ€๋กœ, ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๋ฅผ ์ „๋ถ€ ์ž…๋ ฅ๋ฐ›์•„์„œ ์ €์žฅํ•œ ๋’ค ์ „๋ถ€ ์ถœ๋ ฅํ•  ํ•„์š”๋Š” ์—†๋‹ค. ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๋ฅผ ํ•˜๋‚˜ ๋ฐ›์€ ๋’ค ํ•˜๋‚˜ ์ถœ๋ ฅํ•ด๋„ ๋œ๋‹ค.

์–ด๋–ป๊ฒŒ ํ‘ธ๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค

5.์ž์—ฐ์ˆ˜ N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๋ถ€ํ„ฐ N๊นŒ์ง€ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

ํ•ต์‹ฌ: for๋ฌธ๋งŒ ์“ธ ์ค„ ์•Œ๋ฉด๋จ

import Foundation

let line = Int(readLine()!)!

for i in 1...line {
    print(i)
}
/*
1
2
3
4
5
*/

6.์ž์—ฐ์ˆ˜ N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, N๋ถ€ํ„ฐ 1๊นŒ์ง€ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

ํ•ต์‹ฌ: 5๋ฒˆ ๋ฌธ์ œ ๋ฐ˜๋Œ€๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ˆ?

import Foundation

let line = Int(readLine()!)!

for i in 0...line - 1{
    print(line - i)
}
/*
5
4
3
2
1
*/

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

ํ•ต์‹ฌ: for๋ฌธ์œผ๋กœ ํ•˜๋‚˜ ๋Œ๋ ค์„œ ๋ฐฐ์—ด์— ๋„ฃ์€ ๋‹ค์Œ ๊ทธ ๋ฐฐ์—ด์„ ์ฐจ๋ก€๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

import Foundation

let line = Int(readLine()!)!
var arr = [Int]()
for _ in 1...line{
    let number = readLine()!
    let numberarr = number.components(separatedBy:" ")
    let a = Int(numberarr[0])!
    let b = Int(numberarr[1])!
    arr.append(a+b)
    
}

for i in 0...arr.count-1{
    print("Case #\(i+1): \(arr[i])")
}
/*
Case #1: 2
Case #2: 5
Case #3: 7
Case #4: 17
Case #5: 7
*/

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€