【CODE】Basic Calculator

 

目錄

227. Basic Calculator II

224. Basic Calculator

282. Expression Add Operators


227. Basic Calculator II

Medium

1087198Add to ListShare

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.
class Solution {
public:
    int calculate(string s) {
        char sign='+';
        int num=0;
        stack<int> st;
        for(int i=0;i<s.size();i++){
            if(s[i]>='0' && s[i]<='9') num=num*10+(s[i]-'0');
            if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/' || i==s.size()-1){
                if(sign=='+') st.push(num);
                else if(sign=='-') st.push((-1)*num);
                else if(sign=='*'){
                    int a=st.top();
                    st.pop();
                    st.push(a*num);
                }else if(sign=='/'){
                    int a=st.top();
                    st.pop();
                    st.push(a/num);
                }
                num=0;
                sign=s[i];
            }
        }
        int res=0;
        while(!st.empty()){
            int a=st.top();
            st.pop();
            if(!st.empty()){
                int b=st.top();
                st.pop();
                st.push(a+b);
            }else res=a;
        }
        return res;
    }
};
  • 遇到 ‘ + | - | * | / ’ 或倒數最後一個字符:
  • sign= ‘  +  ’ :st.push(num)
  • sign= ‘  -   ’ :st.push((-1)*num)
  • sign= ‘  *   ’ :top=st.top();st.pop();st.push(top*num);
  • sign= ‘  /   ’ :top=st.top();st.pop();st.push(top/num);
  • sign=s[i],num=0

224. Basic Calculator

Hard

1143116Add to ListShare

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

Example 1:

Input: "1 + 1"
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.
class Solution {
public:
    int calculate(string s) {
        int res = 0, num = 0, sign = 1, n = s.size();
        stack<int> st;
        for (int i = 0; i < n;i++){
            char c = s[i];
            if(c>='0' && c<='9') num=num*10+(c-'0');
            if(c=='+' || c=='-'){
                res += sign * num;
                num = 0;
                sign = (c == '+') ? 1 : -1;
            }else if(c=='('){
                st.push(res);
                st.push(sign);
                res = 0;
                sign = 1;
            }else if(c==')'){
                res += sign * num;
                num = 0;
                res *= st.top();//正還是負
                st.pop();
                res += st.top();
                st.pop();
            }
        }
        res += sign * num;
        return res;
    }
};
  • 只有遇到 ‘(  ’ 才入棧;
  • 遇到 ‘(  ’ :push(res),push(sign),res=0,sign=1
  • 遇到 ‘  )’ :res+=num*sign,res*=st.top();st.pop();res+=st.top();st.pop();num=0;
  • 遇到 ‘  +  ’ :res+=num*sign,num=0,sign=1
  • 遇到 ‘  -   ’ :res+=num*sign,num=0,sign=-1

282. Expression Add Operators

Hard

990154Add to ListShare

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or * between the digits so they evaluate to the target value.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"] 

Example 2:

Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]

Example 3:

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

Example 4:

Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]

Example 5:

Input: num = "3456237490", target = 9191
Output: []
#include"pch.h"
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
/*282. Expression Add Operators
1.DFS,計算出每個s的最終值,超時*/
long long getNum(string s) {
	stack<long long> st;
	long long num = 0;
	char flag = '+';
	for (int i = 0; i < s.size(); i++) {
		if (s[i] >= '0' && s[i] <= '9') num = num * 10 + (s[i] - '0');
		if(s[i]=='+' || s[i]=='-' || s[i]=='*' || i==s.size()-1){
			if (flag == '*') {
				long long a = st.top();
				st.pop();
				st.push(a*num);
			}
			else if (flag == '+') st.push(num);
			else if (flag == '-') st.push(-num);
			flag = s[i];
			num = 0;
		}
	}
	long long res = 0;
	while (!st.empty()) {
		long long a = st.top();
		st.pop();
		if (!st.empty()) {
			long long b = st.top();
			st.pop();
			st.push(a + b);
		}
		else res = a;
	}
	return res;
}
void DFS(string num, int start, int target, vector<string> &out, vector<string> &res) {
	if (start >= num.size()) {
		string s = "";
		for (auto a : out) s += a;
		if (getNum(s) == target) res.push_back(s);
		return;
	}
	int i = start;
	int right = num.size() - i;
	if (num[i] == '0') right = 1;
	for (int j = 1; j <= right; j++) {
		string s = num.substr(i, j);
		out.push_back(s);
		if (i + j != num.size()) {
			out.push_back("+");
			DFS(num, i + j, target, out, res);
			out.pop_back();
			out.push_back("-");
			DFS(num, i + j, target, out, res);
			out.pop_back();
			out.push_back("*");
			DFS(num, i + j, target, out, res);
			out.pop_back();
			out.pop_back();
		}
		else {
			DFS(num, i + j, target, out, res);
			out.pop_back();
		}
	}
	return ;
}
vector<string> addOperators1(string num, int target) {
	vector<string> res,out;
	DFS(num, 0, target,out,res);
	return res;
}
/*2.兩個變量diff和curNum,
一個用來記錄將要變化的值,另一個是當前運算後的值,
而且它們都需要用 long 型的,因爲字符串轉爲int型很容易溢出,
對於加法,diff就是即將要加上的值,
對於減法,diff就是即將要減去的值的相反數,
對於乘法,diff就是上一個diff乘以即將要乘上的數字,
例如,2+3*2,將運算到*2時,上次循環的curNum=5,diff=3,
算完*2後,diff變爲6,並且把之前的+3操作去掉,再加上新的diff,
即(5-3)+6-8.*/
vector<string> addOperators(string num, int target) {
	vector<string> res;
	helper(num, target, 0, 0, "", res);
	return res;
}
void helper(string num, int target, long diff, long curNum, string out, vector<string>& res) {
	if (num.size() == 0 && curNum == target) {
		res.push_back(out); return;
	}
	for (int i = 1; i <= num.size(); ++i) {
		string cur = num.substr(0, i);
		if (cur.size() > 1 && cur[0] == '0') return;
		string next = num.substr(i);
		if (out.size() > 0) {
			helper(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, res);
			helper(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, res);
			helper(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, res);
		}
		else {
			helper(next, target, stoll(cur), stoll(cur), cur, res);
		}
	}
}
int main() {
	vector<string> res = addOperators("3456237490",9191);
	for (auto a : res) cout << a << " ";
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章