开发者

product of string

开发者 https://www.devze.com 2023-03-18 03:45 出处:网络
I need a function which return the product of numbers in the string: SomeFunc(\"1234\") -> 1 * 2 * 3 * 4 = 24

I need a function which return the product of numbers in the string:

SomeFunc("1234") -> 1 * 2 * 3 * 4 = 24

Here is my code:

lists:foldr(fun(X, Y) ->开发者_运维知识库 X * Y end, 1, "1234").

But I get 6497400.

Why and how can I fix the code?


Your code is multiplying the ascii codes of the characters, i.e. 49*50*51*52. In order to get your desired result, use

lists:foldr(fun(X, Y) -> (X-$0)*Y end, 1, "1234")

where $0 is the ASCII code for the character '0'.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号