ScalaNote23-递归应用

直接看递归的案例~

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 于南京市栖霞区

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值