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

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;
}

猜你喜欢

转载自blog.csdn.net/zero_zp/article/details/80250673