View Code of Problem 94

    #include<stdio.h>
    #include<string.h>
    char s[1000],ch;
    int n,k;
    long dfs(int t,char c)
    {
        int i=0,j,a[100];
        long ans;
        while (s[k]!=')')
        {
            if (s[k]=='(')
            {
                k++;
                while (s[k]==' ') k++;
                ch=s[k];
                i++;
                a[i]=dfs(t+1,ch);
            }
            else if (s[k]==' ') k++;
            else if (s[k]>='0'&&s[k]<='9')
            {
                i++;
                a[i]=s[k]-'0';
                k++;
            }
            else k++;
        }
        ans=a[1];
        if (c=='+')
        for (j=2;j<=i;j++)
            ans+=a[j];
        if (c=='-')
        for (j=2;j<=i;j++)
            ans-=a[j];
        if (c=='*')
        for (j=2;j<=i;j++)
            ans*=a[j];
        if (c=='/')
        for (j=2;j<=i;j++)
            ans/=a[j];
        k++;
        return ans;
    }
     
    int main()
    {
        gets(s);
        n=strlen(s);
        k=0;
        while (s[k]!='(')
            k++;
        k++;
        while (s[k]==' ')
            k++;
        ch=s[k];
        printf("%ld\n",dfs(1,ch));
        return 0;
    }

Double click to view unformatted code.


Back to problem 94