【HDU - 1237】简单计算器 (栈模拟)
生活随笔
收集整理的這篇文章主要介紹了
【HDU - 1237】简单计算器 (栈模拟)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題干:
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。?
Input
測試輸入包含若干測試用例,每個測試用例占一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。?
Output
對每個測試用例輸出1行,即該表達式的值,精確到小數點后2位。?
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0Sample Output
3.00 13.36解題報告:
棧的應用,因為運算有優先級,在剛開始考慮乘法和除法,如果運算符是加法,則直接把那個數字壓入棧里,如果是減法,則把那個數的相反數壓入棧里,如果是乘法,則取棧頭的數相乘,pop出后把結果push進去。
AC代碼:
#include<bits/stdc++.h>using namespace std; char s[205]; int main() {while(1) {gets(s);if(s[0] == '0' && strlen(s) == 1) break;stack<double > sk;int tmp = 0,flag=1;for(int i = 0; i<strlen(s); i++) {if(s[i] == ' ') continue;else if(s[i] == '+') flag=1;else if(s[i] == '-') flag=2;else if(s[i] == '*') flag=3;else if(s[i] == '/') flag=4;else {tmp = 0;while(s[i]>='0' && s[i] <= '9') {tmp = tmp*10 + (s[i] - '0');i++;}i--;switch(flag) {case 1 : sk.push(tmp);break;case 2 : sk.push(-tmp);break;case 3 : {double x = sk.top() * tmp;sk.pop();sk.push(x);tmp=0;break;}case 4 : {double x = sk.top() / tmp;sk.pop();sk.push(x);tmp=0;break;}}}}double ans=0;while(!sk.empty()) {ans += sk.top();sk.pop();}printf("%.2f\n",ans);}return 0 ; }AC代碼2:(在https://leetcode-cn.com/problems/basic-calculator-ii/提交)
class Solution { public:int calculate(string s) {stack<int> sk;int sign = 1;for(int i = 0; i<s.length(); i++) {if(s[i] == ' ') continue;else if(s[i] == '+') sign = 1;else if(s[i] == '-') sign = 2;else if(s[i] == '*') sign = 3;else if(s[i] == '/') sign = 4;else {int tmp = 0;while(i < s.length() && s[i]>='0'&&s[i]<='9') {tmp = tmp * 10 + (s[i] - '0');i++;}i--;if(sign == 1) sk.push(tmp);if(sign == 2) sk.push(-tmp);if(sign == 3) {int x = sk.top();sk.pop();sk.push(x*tmp);}if(sign == 4) {int x = sk.top();sk.pop();printf("%d %d",x,tmp);sk.push(x/tmp);}}}int ans = 0;while(sk.size()) {ans += sk.top();sk.pop();}return ans;} };錯誤代碼:
#include<bits/stdc++.h>using namespace std; char s[10000]; int main() {while(1) {gets(s);if(s[0] == '0') break;stack<double > sk;int tmp = 0;for(int i = 0; i<strlen(s); i++) {if(s[i] == ' ') continue;else if(s[i] == '+') sk.push((double)tmp),tmp=0;else if(s[i] == '-') sk.push((double)-tmp),tmp=0;else if(s[i] == '*') {double x = sk.top() * tmp;sk.pop();sk.push(x);tmp=0;}else if(s[i] == '/') {double x = sk.top() / tmp;sk.pop();sk.push(x);tmp=0;}else {tmp = tmp*10 + (s[i] - '0');}}double ans=0;while(!sk.empty()) {ans += sk.top();sk.pop();}printf("%.2f\n",ans);}return 0 ; }總結:
? ?這個錯誤代碼都不知道是什么一個思路,所以做這種題,每一步實現的功能需要很明確,比如我如果要讀入數,那就一次性都讀完,別一個一個讀,會造成最后讀入的一個數讀不進去等問題存在!?
?
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【HDU - 1237】简单计算器 (栈模拟)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 雷军:小米12S Ultra不测DXO了
- 下一篇: 算法讲解 -- 区间dp经典模型与优化(