挑战用很多种方法解决A+B(c++)

1|0写在前面的

本文章主要是博主自己想写。水篇文章。

2|0正常作法

#include<bits/stdc++.h> using namespace std; int main(){ int a,b; cin>>a>>b; cout<<a+b; return 0; }

3|0数组

#include<bits/stdc++.h> using namespace std; int main(){ int a[3]; cin>>a[1]>>a[2]; cout<<a[1]+a[2]; return 0; }

4|0枚举

#include<bits/stdc++.h> using namespace std; int main(){ int a,b; cin>>a>>b; for(int i=INT_MIN;i<=INT_MAX;i++){ if(i==a+b){ cout<<i; break; } } return 0; }

5|0二分

#include<bits/stdc++.h> using namespace std; int main(){ int a,b; cin>>a>>b; int l=INT_MIN,r=INT_MAX; while(l<=r){ int mid=l+r>>1; if(mid==a+b){ cout<<mid; break; } else if(mid<a+b)l=mid+1; else r=mid-1; } return 0; }

6|0前缀和

#include<bits/stdc++.h> using namespace std; int main(){ int a[10],s[10]; for(int i=1;i<=2;i++){ cin>>a[i]; s[i]=s[i-1]+a[i]; } cout<<s[2]-s[0]; return 0; }

7|0表达式

#include<bits/stdc++.h> using namespace std; #define int long long stack<int>num; stack<char>op; map<char,int>h; string s; void eval(){ int b=num.top();num.pop(); int a=num.top();num.pop(); char opt=op.top();op.pop(); if(opt=='+')num.push(a+b); else if(opt=='-')num.push(a-b); else if(opt=='*')num.push(a*b); else if(opt=='/')num.push(a/b); else if(opt=='^')num.push(pow(a,b)); return; } signed main(){ h['+']=1,h['-']=1,h['*']=2,h['/']=2,h['^']=3; int a,b; cin>>a>>b; if(a==0)return cout<<b,0; if(b==0)return cout<<a,0; string aa,bb; if(a<0)s+="0-"; a=abs(a); while(a){ aa+=char(a%10+'0'); a/=10; } reverse(aa.begin(),aa.end()); s+=aa; s+="+"; if(b<0)s+="0-"; b=abs(b); while(b){ bb+=char(b%10+'0'); b/=10; } reverse(bb.begin(),bb.end()); s+=bb; for(int i=0;i<s.size();i++){ if(s[i]>='0'&&s[i]<='9'){ int tmp=0,j=i; while(j<s.size()&&s[j]>='0'&&s[j]<='9'){ tmp=tmp*10+(s[j]-'0'); j++; } num.push(tmp); i=j-1; } else if(s[i]=='('){ op.push(s[i]); } else if(s[i]==')'){ while(op.size()>1&&op.top()!='(')eval(); op.pop(); } else{ while(op.size()&&h[op.top()]>=h[s[i]]) eval(); op.push(s[i]); } } while(op.size())eval(); cout<<num.top(); return 0; }

8|0BFS

持续更新中。


__EOF__

本文作者xdh2012
本文链接https://www.cnblogs.com/xdh2012/p/17780577.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   Xu_dh  阅读(17)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示