C - たくさんの数式 / Many Formulas

本文介绍了一种解决特定字符串数式求和问题的算法,通过二进制思想来枚举所有可能的加法组合,并计算这些组合的总和。算法使用C++实现,能够高效地处理输入字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C - たくさんの数式 / Many Formulas


Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive. You can insert the letter + into some of the positions (possibly none) between two letters in this string. Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

  • 1|S|10
  • All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.


Sample Input 1

Copy
125

Sample Output 1

Copy
176

There are 4 formulas that can be obtained: 1251+2512+5 and 1+2+5. When each formula is evaluated,

  • 125
  • 1+25=26
  • 12+5=17
  • 1+2+5=8

Thus, the sum is 125+26+17+8=176.


Sample Input 2

Copy
9999999999

Sample Output 2

Copy
12656242944
题解:二进制思想。1代表有‘+‘,0代表没有。
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

long long toIntSum(string s)
{
    long long sum=0,tmp=0;
    for (int i=0;i<s.size();i++)
    {
        if(s[i]=='+')
        {
           sum+=tmp;
           tmp=0;
        }
        else
            tmp=tmp*10+s[i]-'0';

    }
    return sum+tmp;
}
int main ()
{
    string str;
    cin>>str;
    int len =str.size()-1,a[11]={0};//加号最多=串长-1;a[i]==0表示i处没有加号,a[i]==1表示i处有加号.
    long long sum=0;
    while(true)
    {
        string s;
        for (int i=0;i<len;i++)
        {
            a[i+1]+=a[i]/2;
            a[i]%=2;
        }
        if(a[len])
            break;
        for (int i=0;i<len;i++)//把加号和数字合成一个串
        {
            s+=str[i];
            if(a[i])
                s+="+";
        }
        s+=str[len];
        sum+=toIntSum(s);
        a[0]++;
    }
    cout<<sum;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值