【HDU - 1237】简单计算器 (栈模拟)
題干:
讀入一個(gè)只包含 +, -, *, / 的非負(fù)整數(shù)計(jì)算表達(dá)式,計(jì)算該表達(dá)式的值。?
Input
測(cè)試輸入包含若干測(cè)試用例,每個(gè)測(cè)試用例占一行,每行不超過(guò)200個(gè)字符,整數(shù)和運(yùn)算符之間用一個(gè)空格分隔。沒(méi)有非法表達(dá)式。當(dāng)一行中只有0時(shí)輸入結(jié)束,相應(yīng)的結(jié)果不要輸出。?
Output
對(duì)每個(gè)測(cè)試用例輸出1行,即該表達(dá)式的值,精確到小數(shù)點(diǎn)后2位。?
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0Sample Output
3.00 13.36解題報(bào)告:
棧的應(yīng)用,因?yàn)檫\(yùn)算有優(yōu)先級(jí),在剛開(kāi)始考慮乘法和除法,如果運(yùn)算符是加法,則直接把那個(gè)數(shù)字壓入棧里,如果是減法,則把那個(gè)數(shù)的相反數(shù)壓入棧里,如果是乘法,則取棧頭的數(shù)相乘,pop出后把結(jié)果push進(jìn)去。
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;} };錯(cuò)誤代碼:
#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 ; }總結(jié):
? ?這個(gè)錯(cuò)誤代碼都不知道是什么一個(gè)思路,所以做這種題,每一步實(shí)現(xiàn)的功能需要很明確,比如我如果要讀入數(shù),那就一次性都讀完,別一個(gè)一個(gè)讀,會(huì)造成最后讀入的一個(gè)數(shù)讀不進(jìn)去等問(wèn)題存在!?
?
?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的【HDU - 1237】简单计算器 (栈模拟)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 雷军:小米12S Ultra不测DXO了
- 下一篇: 沪指重返3400点:芯片股集体大涨