直接看递归的案例~
Exercise01
计算1-50的和!同时使用循环和递归,并且比较执行时间
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Period,Duration}
//单位:毫秒
val time1 = System.currentTimeMillis()
println("Start Time: "+time1)
var s1 = 0
for(i <-1 to 50000){
s1+=i
}
println("s1 = "+s1)
val time2 = System.currentTimeMillis()
println("End Time:"+time2)
println("Execution Time:"+(time2-time1))
Start Time: 1584501495619
s1 = 1250025000
End Time:1584501495624
Execution Time:5
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Period, Duration}
time1: Long = 1584501495619
s1: Int = 1250025000
time2: Long = 1584501495624
def recursiveSum(n:BigInt):BigInt={
if(n==1){
1
}else{
n+recursiveSum(n-1)
}
}
val time1 = System.currentTimeMillis()
println("Start Time: "+time1)
println("s1 = "+recursiveSum(5000))
val time2 = System.currentTimeMillis()
println("End Time:"+time2)
println("Execution Time:"+(time2-time1))
Start Time: 1584502199904
s1 = 12502500
End Time:1584502199905
Execution Time:1
recursiveSum: (n: BigInt)BigInt
time1: Long = 1584502199904
time2: Long = 1584502199905
jupyter中递归次数多好像报错。。。idea中没有这样的问题
Exercise02
求一个List中的最大值。List本身有内置函数,我们也可以用简单的冒泡排序等等
val list= List(1,2,3,4,5)
list.max
list: List[Int] = List(1, 2, 3, 4, 5)
res31: Int = 5
循环方式
var maxValue = 0
for (i<-list){
if (i>maxValue) maxValue=i else maxValue
}
println("maxValue = "+maxValue)
maxValue = 5
maxValue: Int = 5
递归方式
递归需要搞明白tail函数,list.tail返回的是除第一个元素之外的所有元素
def myMax(xs: List[Int]): Int = {
if (xs.isEmpty)
// 如果list为空,抛异常
throw new java.util.NoSuchElementException
// 1.如果只有一个元素,直接返回该元素
//2.后面不停递归,大概逻辑是第一个元素和others的最大值比较
//3.这里myMax被递归用了两次
// println(xs.head)
if (xs.size == 1)
xs.head
else if (xs.head > myMax(xs.tail)) {
xs.head
} else {
myMax(xs.tail)
}
}
myMax(list)
myMax: (xs: List[Int])Int
res50: Int = 5
Exercise03
翻转字符串,这也有好几个方法。
var Str = "abcd"
Str.reverse
Str: String = abcd
res51: String = dcba
def reverse(xs: String): String =
if (xs.length == 1) xs else reverse(xs.tail) + xs.head
reverse(Str)
reverse: (xs: String)String
res52: String = dcba
Exercise04
递归
def factorial(n: Int): Int =
if (n == 0) 1 else n * factorial(n - 1)
factorial(5)
factorial: (n: Int)Int
res53: Int = 120
2020-03-18 于南京市栖霞区