2013-04-26 266 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