scala之-常用递归代替while do while循环
1 递归求和
def getAdd(l:Long): Long ={
if (l<=0) throw new Exception("msg")
if (l == 1) return l
getAdd(l-1)+l
}
getAdd(50).sout
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)))
}
}
3 递归反转字符串 and List
object DiguiReverse {
def main(args: Array[String]): Unit = {
def myReverse(s:String):String = {
if (s.length ==1) s.head.toString
else myReverse(s.tail)+s.head.toString
}
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))
}
}