Skip to content

Commit 9f2fb15

Browse files
committed
순환함수와 기본 예제 2
1 parent df158d1 commit 9f2fb15

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Algorithm/Inflearn/Algorithm-Inflearn/main.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,35 @@ class Recursive {
3838
return n * factorial(n: n - 1)
3939
}
4040
}
41+
42+
// 4. 2진수로 변환하여 출력
43+
func printBinary(n: Int) { // 음이 아닌 정수 n을 이진수로 변환하여 인쇄한다
44+
if n < 2 {
45+
print(n, terminator: "")
46+
} else {
47+
printBinary(n: n / 2) // n을 2로 나눈 몫을 먼저 2진수로 변환하여 인쇄한 후
48+
print(n % 2, terminator: "") // n을 2로 나눈 나머지를 인쇄한다
49+
}
50+
}
51+
52+
// 5. 배열의 합 구하기
53+
// data[0]에서 data[n-1] 까지의 합을 구하여 반환한다.
54+
func sumArray(n: Int, data: [Int]) -> Int {
55+
if n <= 0 {
56+
return 0
57+
} else {
58+
return sumArray(n: n - 1, data: data) + data[n - 1]
59+
}
60+
}
4161
}
4262

4363
let result = Recursive().sum(n: 5)
4464
print("합 예제 결과 : \(result)")
4565

4666
let result2 = Recursive().factorial(n: 4)
4767
print("팩토리얼 예제 결과 : \(result2)")
68+
69+
Recursive().printBinary(n: 5)
70+
71+
let result4 = Recursive().sumArray(n: 4, data: [0, 1, 2, 3])
72+
print("\n배열의 합 구하기 예제 결과 : \(result4)")

0 commit comments

Comments
 (0)