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

如何实现整数所有连续拆分组合的求和函数?求代码修改思路

需求说明

给定一个整数(例如12345),需要计算其所有不改变数字顺序的连续拆分组合的总和,示例拆分形式如下:

12345
1234+5
123+45
123+4+5
12+345
12+34+5
12+3+45
12+3+4+5
1+2345
1+234+5
1+23+45
1+23+4+5
1+2+345
1+2+34+5
1+2+3+45
1+2+3+4+5
已尝试的方案
  • 尝试通过多次除法(div)、取模(mod)运算,以及步长为10^N(N为1到整数位数)的for循环实现,但未成功。
  • 编写的C代码仅能拆分出单个数字并求和,代码如下:
int break_digits(int n) {
    int remain;
    int sum = 0;
    int original_number = n;
    while (n != 0) {
        remain= n % 10;
        sum+=remain;
        n /= 10;
    }
    return  sum;
}
  • 找到一段Python递归字符串拆分代码,原本用于生成字符串的所有非重叠子串组合,现在想修改这段代码适配数字场景,实现输入整数、返回所有连续拆分组合总和的函数,代码如下:
OPEN_BRACKET = '{'
CLOSED_BRACKET = '}'
EMPTY_STRING = ''
 
# Function to break a string into all possible combinations of
# non-overlapping substrings enclosed within parenthesis
def recur(s, i=0, out=EMPTY_STRING):
    if i == len(s):
        print(out)
 
    # consider each substring S[i, j]
    for j in reversed(range(i, len(s))):
        substr = OPEN_BRACKET + s[i:j+1] + CLOSED_BRACKET
 
        # append the substring to the result and recur with an index of the
        # next character to be processed and the result string
        recur(s, j + 1, out + substr)
 
 
if __name__ == '__main__':
    s = 'ABCD'    # input string
    recur(s)
寻求帮助

需要修改上述Python代码的思路或技术提示,以实现目标功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:23:17