抽空继续做作业,时间不连续,进度有快有慢,各位看官,还请多多包涵啊。

1. 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。举例:“Hello”中所有字符的乘积是9415087488L
Ans:

scala> var m : BigInt = 1
m: BigInt = 1

scala> for (i <- "Hello") { m = m * i.toInt}

scala> println(m)
9415087488

2. 题目如上一题,但不用循环
Ans:

scala> "Hello".foldLeft(List[BigInt]())((b,a) => a :: b).reverse.reduce(_ * _)
res157: BigInt = 9415087488

or:

scala> "Hello".foldLeft(1L)(_ * _)
res158: Long = 9415087488

3. 编写一个函数product(s: String),计算上面的乘积
Ans:

scala> def product(s: String) = {
     | s.foldLeft(1L)(_ * _)
     | }
product: (s: String)Long

scala> product("Hello")
res1: Long = 9415087488

4. 用递归函数实现上面的乘积
Ans:

scala> def product(s: String) : BigInt = {
     |     if (s.length <= 0) 1
     |     else s.head.toInt * product(s.tail)
     | }
product: (s: String)BigInt

scala> product("Hello")
res1: BigInt = 9415087488

enter image description here