2013-04-26 265 views
23
def multiplyStringNumericChars(list: String): Int = { 
    var product = 1; 
    println(s"The actual thing + $list") 
    list.foreach(x => { println(x.toInt); 
         product = product * x.toInt; 
        }); 

    product; 
}; 

這是一個函數,它像12345一個字符串,並應返回的1 * 2 * 3 * 4 * 5結果。但是,我回來沒有任何意義。實際返回從CharInt的隱式轉換是什麼?斯卡拉炭爲int轉換

它似乎是將48添加到所有值。如果我做product = product * (x.toInt - 48)的結果是正確的。

+9

一個字符,toInt回報相應的字符代碼。使用x.asDigit獲取與數字相對應的整數(如果包含字母,則該數字最大爲36)。 – 2013-04-26 17:24:24

回答

50

它確實有道理:那是how characters encoded in ASCII table:0字符映射到十進制48,1映射到49等等。所以基本上,當你將char轉換爲int,所有你需要做的是隻減去「0」:

scala> '1'.toInt 
// res1: Int = 49 

scala> '0'.toInt 
// res2: Int = 48 

scala> '1'.toInt - 48 
// res3: Int = 1 

scala> '1' - '0' 
// res4: Int = 1 

或者只是使用x.asDigit,作爲@Reimer說

scala> '1'.asDigit 
// res5: Int = 1