從零起步看算法(第十一天 4.16)
//q12 表達式求值
1.首先想到的是先算乘法再算加法
2.編程過程中瞭解到了一個函數isdigit()//頭文件 #include<cctype>
https://blog.csdn.net/liuweiyuxiang/article/details/50850104
3.取後四位,或限制位數的問題,目前積累了兩個想法,一個是拆數,另一個是取餘。
ac版:
https://blog.csdn.net/Liukairui/article/details/79073235
以節點和標誌來初始化,存儲,加乘。
仍需領悟
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<assert.h>
#include<cctype>//判斷字符
using namespace std;
int main(){
long long ans,add,mul;//ans爲最後輸出值
ans=0;
mul=1;
add=0;
char buf;//一個字符一個字符處理
//string str;
while(scanf("%c",&buf)==1&&buf!=10){//輸入的形式
if(isdigit(buf)){//add存數
add=add*10;
add+=buf-'0';
}
if(buf=='+'){
if(mul!=1){//後乘數
mul*=add;
add=0;
ans=ans%10000;
ans+=mul%10000;
ans=ans%10000;
mul=1;
}
else{//前無乘數 簡答的加數取餘
ans=ans%10000;
ans+=add%10000;
ans=ans%10000;
add=0;
}
}
if(buf=='*'){
mul*=add;
mul=mul%10000;
ans=ans%10000;
add=0;
}
}
if(mul!=1){//以乘法結束
mul*=add;
ans+=mul;
}
else{
ans+=add%10000;
ans=ans%10000;
}
cout<<ans%10000<<endl;
return 0;
}
long long ans,add,mul;//ans爲最後輸出值
ans=0;
mul=1;
add=0;
char buf;//一個字符一個字符處理
//string str;
while(scanf("%c",&buf)==1&&buf!=10){//輸入的形式
if(isdigit(buf)){//add存數
add=add*10;
add+=buf-'0';
}
if(buf=='+'){
if(mul!=1){//後乘數
mul*=add;
add=0;
ans=ans%10000;
ans+=mul%10000;
ans=ans%10000;
mul=1;
}
else{//前無乘數 簡答的加數取餘
ans=ans%10000;
ans+=add%10000;
ans=ans%10000;
add=0;
}
}
if(buf=='*'){
mul*=add;
mul=mul%10000;
ans=ans%10000;
add=0;
}
}
if(mul!=1){//以乘法結束
mul*=add;
ans+=mul;
}
else{
ans+=add%10000;
ans=ans%10000;
}
cout<<ans%10000<<endl;
return 0;
}