题解 | #四则运算#

四则运算

http://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

#include <stdio.h>

static int i = 0;

static int compute(char *str)
{
    if(!str)
    {
        return -1;
    }
    int stack[1000] = {0};
    int top = -1;
    int len = strlen(str);
    char flag = '+';    /* 默认是+号 */
    while(i <= len)
    {
        int num = 0;
        /* 判断是否是-号 */
        if(str[i] == '-')
        {
            flag = '-';
            i++;
        }
        
        /* 如果有括号,要先计算括号里面的 */
        if(str[i] == '{' || str[i] == '[' || str[i] == '(')
        {
            i++;
            num = compute(str);
        }
        
        /* 数字可能是两位或两位以上,这个方法获取完整的数字 */
        while(str[i] >= '0' && str[i] <= '9')
        {
            num = num * 10 + str[i]-'0';
            i++;
        }
        //printf("flag = [%c]\n", flag);
        switch(flag)
        {
            case '+':
                {
                    stack[++top] += num;
                    //printf("stack[%d] = [%d], num = [%d]\n", top, stack[top],num);
                }
                break;
            case '-':
                {
                    stack[++top] -= num;
                    //printf("stack[%d] = [%d], num = [%d]\n", top, stack[top],num);
                }
                break;
            case '*':
                {
                    stack[top] *= num;
                    //printf("stack[%d] = [%d], num = [%d]\n", top, stack[top],num);
                }
                break;
            case '/':
                {
                    stack[top] /= num;
                    //printf("stack[%d] = [%d], num = [%d]\n", top, stack[top],num);
                }
                break;
        }
        flag = str[i];
        
        /* 括号里面的计算结束 */
        if(str[i] == '}' || str[i] == ']' || str[i] == ')')
        {
            i++;
            break;
        }
        i++;
    }
    
    int res = 0;
    for(int j = 0; j <= top; j++)
    {
        res += stack[j];
    }
    return res;
}

int main()
{
    char str[1000] = {0};
    scanf("%s", str);
    int res = compute(str);
    printf("%d\n", res);
    return 0;
}

打印结果和解析

3+2*{1+2*[-4/(8-6)+7]}

flag = [+]
stack[0] = [3], num = [3]
flag = [+]
stack[1] = [2], num = [2]

//进入{}号
flag = [+]
stack[0] = [1], num = [1]
flag = [+]
stack[1] = [2], num = [2]

//进入[]号
flag = [-]
stack[0] = [-4], num = [4]

//进入()号
flag = [+]
stack[0] = [8], num = [8]
flag = [-]
stack[1] = [-6], num = [6]
//退出()号

flag = [/]
stack[0] = [-2], num = [2]
//退出[]号

flag = [+]
stack[1] = [7], num = [7]
//退出{}号

flag = [*]
stack[1] = [10], num = [5]
flag = [*]
stack[1] = [22], num = [11]
25
全部评论

相关推荐

字节 飞书绩效团队 (n+2) * 15 + 1k * 12 + 1w
点赞 评论 收藏
分享
10-27 17:26
东北大学 Java
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务