TOP101题解 | BM49#表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* @author Senky
* @date 2023.08.25
* @par url https://www.nowcoder.com/creation/manager/content/584337070?type=column&status=-1
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
int solve(char* s )
{
// write code here
int len = strlen(s), num_stk[108], num_idx = -1, sign_idx = -1, op = 0, op_l, op_r;
char sign_stk[108], ch;
for(int i=0; i<len; i++)
{
if((ch=s[i])>='0' && ch<='9')
{
op = ch-48;
int j = i+1;
while(j<len && (ch=s[j])>='0' && ch<='9'){ op = 10*op+ch-48; j++; }
i = j-1;
num_stk[ ++num_idx ] = op; continue;
}
if(ch=='+' || ch=='-')
{
if( !i )
{
num_stk[ ++num_idx ] = 0;
sign_stk[ ++sign_idx ] = ch;
continue;
}
while(sign_idx!=-1 && sign_stk[sign_idx]!='(')
{
op_r = num_stk[ num_idx-- ];
op_l = num_stk[num_idx];
switch(sign_stk[ sign_idx-- ])
{
case '+' : { num_stk[num_idx] = op_l+op_r; break; }
case '-' : { num_stk[num_idx] = op_l-op_r; break; }
case '*' : { num_stk[num_idx] = op_l*op_r; break; }
}
}
sign_stk[ ++sign_idx ] = ch;
continue;
}
if(ch == '*')
{
if(sign_stk[sign_idx] == '*'){
op_r = num_stk[ num_idx-- ];
op_l = num_stk[num_idx];
num_stk[num_idx] = op_l*op_r;
sign_idx--;
}
sign_stk[ ++sign_idx ] = '*';
continue;
}
if(ch == '('){ sign_stk[ ++sign_idx ] = '('; continue; }
while(sign_stk[sign_idx] != '(')
{
op_r = num_stk[ num_idx-- ];
op_l = num_stk[num_idx];
switch(sign_stk[ sign_idx-- ])
{
case '+' : { num_stk[num_idx] = op_l+op_r; break; }
case '-' : { num_stk[num_idx] = op_l-op_r; break; }
case '*' : { num_stk[num_idx] = op_l*op_r; break; }
}
}
sign_idx--;
}
while(sign_idx != -1)
{
op_r = num_stk[ num_idx-- ];
op_l = num_stk[num_idx];
switch(sign_stk[ sign_idx-- ])
{
case '+' : { num_stk[num_idx] = op_l+op_r; break; }
case '-' : { num_stk[num_idx] = op_l-op_r; break; }
case '*' : { num_stk[num_idx] = op_l*op_r; break; }
}
}
return num_stk[0];
}
#TOP101#TOP101-BM系列 文章被收录于专栏
系列的题解
查看5道真题和解析