forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.kt
55 lines (46 loc) · 1.05 KB
/
solution.kt
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
48
49
50
51
52
53
54
55
package com.igorwojda.integer.addupto
// Kotlin idiomatic solution
private object Solution1 {
private fun addUpTo(n: Int): Int {
return (1..n).sum()
}
}
// Kotlin idiomatic solution
private object Solution2 {
private fun addUpTo(n: Int): Int {
return (0..n).fold(0) { accumulated, current -> accumulated + current }
}
}
// Recursive solution
private object Solution3 {
private fun addUpTo(n: Int): Int {
if (n == 1) {
return 1
}
return n + addUpTo(n - 1)
}
}
// Time Complexity: O(1)
// Mathematical formula
private object Solution4 {
private fun addUpTo(n: Int): Int {
return n * (n + 1) / 2
}
}
// Time Complexity: O(n)
// Iterative solution
private object Solution5 {
private fun addUpTo(n: Int): Int {
var total = 0
(0..n).forEach { total += it }
return total
}
}
// Iterative solution
private object Solution6 {
private fun addUpTo(n: Int): Int {
var total = 0
repeat(n + 1) { total += it }
return total
}
}