You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ELM语言中计算数字加自身数位和的替代实现方法咨询

实现思路说明

下面提供两种和现有字符串转列表思路不同的实现方式:

1. 纯数值运算实现(无类型转换,性能更优)

核心逻辑是通过取模、整除操作逐位提取数位累加,全程不需要做整数和字符串的类型转换,也不需要生成中间列表,适合大整数输入场景:

computeNextValue : Int -> Int
computeNextValue input =
    let
        -- 尾递归累加数位和
        sumDigits n acc =
            if n == 0 then
                acc
            else
                sumDigits (n // 10) (acc + modBy 10 n)
    in
    -- 这里加abs是兼容负数输入,若业务限定输入为非负整数可直接传input
    input + sumDigits (abs input) 0

测试验证:输入123返回129,输入35返回43,符合要求。

2. 字符串折叠简化实现

不需要拆分字符串为列表,直接通过String.foldl遍历字符计算数位和,代码更精简,也避免了filterMap的开销:

computeNextValue : Int -> Int
computeNextValue input =
    let
        addDigit char sum =
            case Char.toCode char of
                -- 直接通过ASCII码计算数位值,比调用String.toInt效率更高
                code | code >= 48 && code <= 57 -> sum + (code - 48)
                _ -> sum
    in
    input + String.foldl addDigit 0 (String.fromInt <| abs input)

内容的提问来源于stack exchange,提问作者smcroissant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:24:00