首页 > 试题广场 >

简单四则运算问题描述:输入一个只包含个位数字的简单四则运算表

[问答题]

简单四则运算问题描述:输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值

注:

1、表达式只含 +, -, *, / 四则运算符,不含括号

2、表达式数值只包含个位整数(0-9),且不会出现 0作为除数的情况

3、要考虑加减乘除按通常四则运算规定的计算优先级

4、除法用整数除法,即仅保留除法运算结果的整数部分。比如 8/3=2。输入表达式保证无0作为除数情况发生

5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,除此之外不含其它任何字符,不会出现计算溢出情况。

要求实现函数: int calculate(int len,char *expStr) 

【输入】  int len: 字符串长度; 

          char *expStr: 表达式字符串; 

【输出】  无

【返回】  计算结果

 示例

1)  输入:char *expStr = “1+4*5-8/3”

      函数返回:19 

 2)  输入:char *expStr = “8/3*3”

      函数返回:6

推荐
#include <stdio.h>
#include <string.h>
#include "assert.h"
struct stack
{
    //存放后续排列的表达式,模拟栈
    char str[80];
    int top;
};
struct sstack
{
    //存放计算表达式的值,模拟栈???
    int str[80];
    int top;
};
int calculate(int len, char *expStr)
{
    char *postexp = new char[len + 1];
    stack opstack;
    sstack calstack;
    calstack.top = -1;
    opstack.top = -1;
    int i = 0;
    int k = 0;
    while (expStr[i] != '\0')
    {
        if (expStr[i] >= '0' && expStr[i] <= '9')
        {
            postexp[k++] = expStr[i];
        }
        else if (expStr[i] == '+' || expStr[i] == '-')
        {
            while (opstack.top >= 0)
            {
                postexp[k++] = opstack.str[opstack.top--];
            }
            opstack.top++;
            opstack.str[opstack.top] = expStr[i];
        }
        else if (expStr[i] == '*' || expStr[i] == '/')
        {
            while (opstack.top >= 0 && (opstack.str[opstack.top] == '*'
                                        || opstack.str[opstack.top] == '/'))
            {
                postexp[k++] = opstack.str[opstack.top--];
            }
            opstack.top++;
            opstack.str[opstack.top] = expStr[i];
        }
        i++;
    }
    while (opstack.top >= 0)
    {
        postexp[k++] = opstack.str[opstack.top--];
    }
    int temp1 = 0;
    int temp2 = 0;
    for (i = 0; i < len; i++)
    {
        if (postexp[i] >= '0' && postexp[i] <= '9')
        {
            calstack.top++;
            calstack.str[calstack.top] = postexp[i] - '0';
        }
        else if (postexp[i] == '+')
        {
            temp1 = calstack.str[calstack.top--];
            temp2 = calstack.str[calstack.top];
            calstack.str[calstack.top] = temp2 + temp1;
        }
        else if (postexp[i] == '-')
        {
            temp1 = calstack.str[calstack.top--];
            temp2 = calstack.str[calstack.top];
            calstack.str[calstack.top] = temp2 - temp1;
        }
        else if (postexp[i] == '*')
        {
            temp1 = calstack.str[calstack.top--];
            temp2 = calstack.str[calstack.top];
            calstack.str[calstack.top] = temp2 * temp1;
        }
        else if (postexp[i] == '/')
        {
            temp1 = calstack.str[calstack.top--];
            temp2 = calstack.str[calstack.top];
            calstack.str[calstack.top] = temp2 / temp1;
        }
    }
    printf("%d\n", calstack.str[calstack.top]);
    return calstack.str[calstack.top];
}
main()
{
    char *expStr = "6+8*4-9/2";
    int len = strlen(expStr);
    calculate(len, expStr);
    return 0;
}

编辑于 2015-02-06 15:54:13 回复(0)
一次入栈计算乘除法 再次出栈计算加减法 即可
发表于 2015-09-18 19:36:21 回复(0)
private static int calculate(String str) {
        int size = str.length();
        if (size == 0) {
            return 0;
        }
        Stack<Integer> num = new Stack<>();
        Stack<Character> op = new Stack<>();

        for (int i = 0; i < size; i++) {
            char temp = str.charAt(i);
            // 数字,利用字符强转int为该字符的ascii码的特点直接进行比较,'0'的ascii为48,'9'的ascii为57
            if (temp >= 48 && temp <= 57) {
                // 将字符'0'转换为数字0
                num.push(Character.getNumericValue(temp));
            } else if (temp == 43 || temp == 45) {
                // "+"的ascii为43,"-"的ascii为45
                op.push(temp);
            } else {
                // 运算符 乘除
                Integer pop = num.pop();
                char nextNum = str.charAt(++i);
                if (temp == 42) {
                    //"*"的ascii为42
                    num.push(pop * Character.getNumericValue(nextNum));
                } else if (temp == 47) {
                    //"/"的ascii为47
                    num.push(pop / Character.getNumericValue(nextNum));
                }
            }
        }
        // 加减操作
        while (!op.empty()) {
            Character pop = op.remove(0);
            Integer a = num.remove(0);
            Integer b = num.remove(0);
            if (pop == 43) {
                num.add(0, a + b);
            } else if (pop == 45) {
                num.add(0, a - b);
            }
        }

        return num.peek();
    }

发表于 2021-08-29 16:59:05 回复(0)
<p>先取一遍运算符号,放到一个二维数组里,并存放运算符(其实只要标记运算优先级)的位置。根据这个map去先做乘除法,再做加减法</p><p>,即可。</p>
发表于 2020-10-15 22:35:06 回复(0)
“”“
用栈存储带符号数字,符号为数字前的符号,第一个数字默认符号为‘+’;
遇到 ‘*’,‘/’,将栈中最后元素与当前元素计算,将计算结果存入栈中;
对栈求和即可。
”“”
def cal(s):
    stack = []
    sign = 1
    op = '+'
    for ch in s:
        if ch.isdigit():
            if op == '-'&nbs***bsp;op == '+':
                stack.append(int(ch) * sign)
            elif op == '*':
                stack[-1] = stack[-1] * int(ch)
            elif op == '/':
                stack[-1] = int(stack[-1] / int(ch))
        elif ch == '-':
            op = ch
            sign = -1
        else:
            op = ch
    return sum(stack)

类似题型:
LeetCode 224, 16.26
编辑于 2020-04-09 15:00:22 回复(0)
def solution(inputstr):
    stack = []
    i = 0
    while i < inputstr.__len__():
        if inputstr[i] in ['*', '/']:
            if inputstr[i] == '*':
                i += 1
                stack.append(int(inputstr[i]))
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(p1 * p2)
            elif inputstr[i] == '/':
                i += 1
                stack.append(int(inputstr[i]))
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(p2 // p1)
        else:
            if inputstr[i] in ['+', '-']:
                stack.append(inputstr[i])
            else:
                stack.append(int(inputstr[i]))
        i += 1


    if stack.__len__()==1:
        return stack.pop()
    else:
        inputstr=stack
    stack = []
    i = 0
    while i < inputstr.__len__():
        if inputstr[i] in ['+', '-']:
            if inputstr[i] == '+':
                i += 1
                stack.append(int(inputstr[i]))
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(p1 + p2)
            elif inputstr[i] == '-':
                i += 1
                stack.append(int(inputstr[i]))
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(p2 - p1)
        else:
            stack.append(int(inputstr[i]))
        i += 1
    return stack.pop()

发表于 2020-03-10 23:48:40 回复(0)
/*******不知道字符串数组能不能用string类替代,我写的是用string类输入的************/

#include<iostream>
#include<string>
using namespace std;
int calculate(int len, string expStr)
{
int *Number = new int;
int i, j=0;
int Result = 0;
Number[0] = expStr[0] - '0';
for (i = 1; i < len; i++)
{
if (expStr[i] == '+')
{
Number[j] = Number[j];
Number[j + 1] = expStr[i + 1] - '0';
j = j + 1;
}
if(expStr[i]=='-')
{
Number[j] = Number[j];
Number[j + 1] = 0 - (expStr[i + 1] - '0');
j = j + 1;
}
if (expStr[i] == '*')
{
Number[j] = Number[j] * (expStr[i + 1] - '0');
}
if (expStr[i]=='/')
{
Number[j] = Number[j] / (expStr[i + 1] - '0');
}
++i;
}
for (i = 0; i < j+1; i++)
{
Result = Result + Number[i];
}
delete Number;
cout << Result << endl;
return 0;
}
int main()
{
string Str;
int N;
cin >> Str;
N = Str.size();
calculate(N,Str);
return 0;
}
编辑于 2016-07-10 10:30:21 回复(0)
可用逆波兰表达式完成
发表于 2016-03-01 20:59:06 回复(0)
int calculate(int len,char *expStr)
{
#define getN(x) (*(x) - '0')
char * pstart = expStr;
char * pNextSequence = NULL;
char * pend = expStr + len;
int result_plus_div = 1;
int result = getN(pstart);

pstart += 1;

while(pstart < pend)
{
if(*pstart == '+' || *pstart == '-' )
{
pNextSequence = pstart + 1;
result_plus_div = getN(pNextSequence);
while(pNextSequence + 1 < pend)//此时pNextEnd 是数字,且pNextEnd + 1不是最后一个数字
{
pNextSequence++; //移到符号位置
if(*pNextSequence == '*')
{
result_plus_div *= getN(++pNextSequence);
}
else if(*pNextSequence == '/')
{
result_plus_div /= getN(++pNextSequence);
}
else //此时pNextEnd是 +或者-
{
break;
}
}
//退出while,此时 pNextEnd是 最后一个数字 或者是 +或-
*pstart == '+' ? result += result_plus_div : result -= result_plus_div;//把连续的计算结果和相邻的左值相加
pstart = pNextSequence;
if(pstart + 1 == pend)//如果pstart是最后一个数字
break;
}else //(*pstart == '*' || *pstart == '/')//如果一开始就是乘除法开头的话会走这里,其他情况不会走人这个分支
{
*pstart == '*' ? result *= getN(pstart + 1) : result /= getN(pstart + 1); 
pstart+=2;
}
}// end-while

return result;
}
发表于 2015-01-08 22:17:42 回复(2)