控制結構與函式練習(二)

2gua發表於2013-02-04

抽空繼續做作業,時間不連續,進度有快有慢,各位看官,還請多多包涵啊。

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

相關文章