# 224-m-Basic Calculator

132人阅读 评论(0)

int calculate(char* s) {
int result = 0;
int n = 10240;
int numstack[n];
char operastack[n];
memset(numstack, 0, sizeof(int) * n);
memset(operastack, 0, sizeof(char) * n);
char *sp = s;
char *nums = "1234567890";
char *operas = "(+-";
char *plusMinus = "+-";
char left = '(', right = ')';

int num = 0;
int indexn = 0, indexo = 0;
bool isKuohao = false;
while (*sp != '\0') {
if (strchr(nums, *sp)) { //操作数入栈
while (strchr(nums, *sp) && *sp != '\0') {
num = num * 10 + *sp - '0';
sp++;
}
numstack[indexn] = num;
indexn++;
if (indexn > 1 && strchr(plusMinus, operastack[indexo - 1])) { //操作数大于1且操作栈最后一个是可运算符则直接运算
int temp = 0;
if (operastack[indexo - 1] == '+')
temp = numstack[indexn - 1] + numstack[indexn - 2];
else
temp = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = temp;
indexn--;
indexo--;
}
}
if (strchr(operas, *sp) && *sp != '\0') { //操作符入栈
num = 0;
operastack[indexo] = *sp;
indexo++;
if (indexo > 1 && strchr(plusMinus, operastack[indexo - 1]) && strchr(plusMinus, operastack[indexo - 2])) {
//连续两个为可操作符时则计算前一个
int temp = 0;
if (operastack[indexo - 2] == '+')
temp = numstack[indexn - 1] + numstack[indexn - 2];
else
temp = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = temp;
indexn--;
operastack[indexo - 2] = operastack[indexo - 1];
indexo--;
}
}
if (*sp == right) { //遇到右括号,则退栈运算
if (operastack[indexo - 1] == '(')
indexo--;
else
{
int tempn = 0;
char tempo = operastack[indexo - 1];
if (tempo == '+')
tempn = numstack[indexn - 2] + numstack[indexn - 1];
else
tempn = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = tempn;
indexn--;
indexo -= 2;
}
isKuohao = true;
}
sp++;
}
if (isKuohao && indexo > 0) {
char tempo = operastack[0];
if (tempo == '+')
numstack[0] = numstack[0] + numstack[1];
else if (tempo == '-')
numstack[0] = numstack[0] - numstack[1];
}
result = numstack[0];

return result;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：21566次
• 积分：1470
• 等级：
• 排名：千里之外
• 原创：128篇
• 转载：6篇
• 译文：0篇
• 评论：0条
文章分类
阅读排行
评论排行