scala之-用递归代替while do while循环

scala之-常用递归代替while do while循环

1 递归求和

    //1 计算1-50的和
    def getAdd(l:Long): Long ={
      if (l<=0) throw new Exception("msg")
      if (l == 1) return l
      getAdd(l-1)+l
    }

		getAdd(50).sout //1250

2 递归求最大值


/**
 * 递归求最大值
 */
object DiguiMax {
  def main(args: Array[String]): Unit = {

    //定义方法
    def maxVal(list: List[Int]): Int = {

      if (list.isEmpty)
        throw new RuntimeException("THERE IS A BIG EXCEPTION!~")
      if (list.size == 1)
        list.head
      else if (list.head > maxVal(list.tail)) list.head
      else maxVal(list.tail)
    }

		//使用方法
    println(maxVal(List(1, 2, 3, 4, 5, 100, 10000, 23))) //10000
  }
}

3 递归反转字符串 and List

/**
 * 递归反转String类型的字符串,可适用于List
 */
object DiguiReverse {
  def main(args: Array[String]): Unit = {

    def myReverse(s:String):String = {
      if (s.length ==1) s.head.toString //如果字符串的长度为1,那么不需要翻转
      else myReverse(s.tail)+s.head.toString //如果字符串不为1,将字符串的tail字符串与head交换位置,同时反转tail
    }

    println(myReverse("123456789"))

  }
}

4 递归求阶乘

object DiguiJieCheng {
  def main(args: Array[String]): Unit = {

    def getJieCheng(n: Int): Int = {
      if (n == 0) 1 else getJieCheng(n - 1) * n
    }

    println(getJieCheng(2))
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值