文章目录
Scala递归编程练习
1. 编程范式
2. 应用实例
实例一
def getRes(): Unit = {
var res = BigInt(0)
var num = BigInt(1)
var maxVal = BigInt(100000000)
while (num <= maxVal) {
res += num
num += 1
}
println(res)
}
def getRecurisveRes(n: BigInt, max: BigInt): BigInt = {
if (n == max) {
n
} else {
n + getRecurisveRes(n + 1, max)
}
}
实例二
def getMax(list: List[Int]): Int = {
if (list.isEmpty) {
throw new java.util.NoSuchElementException
}
if (list.size == 1) {
list.head
} else if (list.head > getMax(list.tail)) {
list.head
} else {
getMax(list.tail)
}
}
实例三
def strReverse(str: String): String = {
if (str.length == 1) {
str
} else {
strReverse(str.tail) + str.head
}
}
实例四
def getFactorial(n: BigInt): BigInt = {
if (n == 1) {
n
} else {
n * getFactorial(n - 1)
}
}
实例五
def getFib(n: Int): Int = {
count += 1
if (n == 1 || n == 2) {
1
} else {
getFib(n - 1) + getFib(n - 2)
}
}
3. 测试代码
import java.util.Date
import java.text.SimpleDateFormat
object RecursiveDemo01 {
var count = 1
def main(args: Array[String]): Unit = {
val start: Date = new Date()
val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val startDate = dateFormat.format(start)
println(startDate)
println(getFib(40))
println(count)
val end: Date = new Date()
val endDate = dateFormat.format(end)
println(endDate)
}
}
☆