Basic Calculator II

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

Example 1:
Input:"3+2*2"
Output: 7

Example 2:
Input:" 3/2 "
Output: 1

Example 3:
Input:" 3+5 / 2 "
Output: 5

Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.

实现基本计算器来评估简单的表达式字符串。

表达式字符串仅包含非负整数,+, - ,*,/运算符和空格。 整数除法应截断为零。

注意
您可以假设给定的表达式始终有效。
不要使用eval内置库函数。

2,题目思路

对于这道题,要求获得一个基本数字运算的字符串的计算结果。

题目中给出的字符串,是一个只含有加减乘除的计算式,因此,在读取的字符串的过程中,可以利用istringstream,一般来说,如果只是读取字符,那么是利用空格进行分隔的。
而如果是不同的数据类型,则是按照数据类型进行读取的。
例子:

	string s = "+3/22+1+";
    istringstream in(s);

    char op;
    int num;
    while(in >> op){
        cout<<op<<endl;
        in>>num;
        cout<<num<<endl;
    }

在这里插入图片描述
在这道题上,我们为了方便读取,我们在字符串的最前和最后都加上’+’,方便进行读取。

3,代码实现

static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    int calculate(string s) {
        istringstream in('+' + s + '+');
        int total = 0;
        int num = 0;
        int n = 0;
        char op;
        while(in >> op){
            if(op == '+'){
                total += num;
                in >> num;
            }
            else if(op == '-'){
                total += num;
                in >> num;  //获得该符号之后的处理对象
                num = -num;
            }
            else if(op == '*'){
                in >> n;
                num *= n;
            }
            else{
                in >> n;
                num /= n;
            }
        }
        return total;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值