0
点赞
收藏
分享

微信扫一扫

scala学习复习笔记超详细(递归编程练习)

两岁时就很帅 2022-04-17 阅读 89
scala

文章目录

Scala递归编程练习

1. 编程范式

2. 应用实例

实例一

  /**
    * 使用while求1-100000000(一亿)的求和
    */
  def getRes(): Unit = {
    var res = BigInt(0)
    var num = BigInt(1)

    // 一亿条数据
    var maxVal = BigInt(100000000)
    while (num <= maxVal) {
      res += num
      num += 1
    }
    println(res)
  }
  /**
    * 使用递归完成
    * @param n
    * @param max
    * @return
    */
  def getRecurisveRes(n: BigInt, max: BigInt): BigInt = {
    if (n == max) {
      n
    } else {
      n + getRecurisveRes(n + 1, max)
    }
  }

实例二

  /**
    * 使用递归完成求List中的最大值
    * @param list
    * @return
    */
  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)
    }
  }

实例三

  /**
    * 使用递归完成字符串的反转
    * @param str 输入的字符串
    * @return 
    */
  def strReverse(str: String): String = {
    if (str.length == 1) {
      str
    } else {
      strReverse(str.tail) + str.head
    }
  }

实例四

/**
  * 递归求阶乘
  * @param n
  * @return
  */
def getFactorial(n: BigInt): BigInt = {
  if (n == 1) {
    n
  } else {
    n * getFactorial(n - 1)
  }
}

实例五

  /**
    * 递归求斐波那契数列
    * @param n
    * @return
    */
  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

/**
  * @Date 2021/4/4 15:55
  * @Version 10.21
  * @Author DuanChaojie
  */
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)

    //getRes()
    //println(getRecurisveRes(1, BigInt(1000)))
    //println(getMax(List(1, 2, 3, 4, 5, 6, 7, 8, 9, 35, 3, 5)))
    //println(strReverse("HELLO"))
    //println(getFactorial(13))
    /**
      * 1 1 2  ...
      * 分析函数都调用了多少次
      *
      * 输入数:4 5  6  7  8   9  10  11  12   13   14   15    21       40
      * 结  果:3 5  8 13  21  34 55  89  144  233  377  610   10946   102334155
      * 调用数:6 10 16 26 42  68 110 178 288  466  754  1220  21892   204668310
      */
    println(getFib(40))
    println(count)

    val end: Date = new Date()
    val endDate = dateFormat.format(end)
    println(endDate)

  }
}

举报

相关推荐

0 条评论