leetcode 手写计算器 方法总结

1.leetcode 227 Basic calculator 我目前见过的最好的解法

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

AC code  

pop 代表上一个是+还是-

pv 代表上一个+ 或者 - 后面的数字是多少

class Solution {
public:
    int calculate(string s) {
        istringstream in("+"+ s);
        long long num = 0;
        long long cv = 0;
        int pv = 0;
        char cop = '#';
        char pop = '#';
        while(in >> cop)
        {
            in >> num;
            if (cop == '+')
            {
                cv += num;
                pv = num;
                pop = cop;
            }
            else if (cop == '-')
            {
                cv -= num;
                pv = num;
                pop = cop;
            }
            else if (cop == '*')
            {
                if (pop == '+') cv = cv - pv + pv*num;
                else if (pop == '-') cv = cv + pv - pv*num;
                pv = pv * num;
                
            }
            else if (cop == '/')
            {
                if (pop == '+') cv = cv - pv + pv/num;
                else if (pop == '-') cv = cv + pv - pv/num;
                pv = pv/num;
            }
        }
        return cv;
    }
};

2.带括号的四则运算

op != ')'

先判空 再判( 再判数 后判op

#include <vector>
#include <iostream>
#include <string>
using namespace  std;

int parseNum(string s, int& i)
{
	long long num = 0;
	while (i < s.size() && s[i] >= '0' && s[i] <= '9') num = 10 * num + s[i++] - '0';
	return num;
}

int parseExpr(string s, int& i)
{
	char op = '+';
	long long  n = 0;
	vector<int> nums;
	long long res = 0;
	for (; i < s.size() && op != ')'; i++)
	{
		char c = s[i];
		if (c == ' ') continue;
		else if (c == '(') n = parseExpr(s, ++i);
		else if (c >= '0' && c <= '9') n = parseNum(s, i);

		switch (op)
		{
			case '+':
				nums.push_back(n);
				break;
			case '-':
				nums.push_back(-n);
				break;
			case '*':
				nums.back() *= n;
				break;
			case '/':
				nums.back() /= n;
				break;
		}
		op = s[i];
	}
	for (int num : nums) res += num;
	return res;
}

int calculate(string s)
{
	int i = 0;
	return parseExpr(s, i);
}


int main() {
	string s;
	while (getline(cin , s))
	{	
		cout << calculate(s) << endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值