# A + B Problem
这一道看似简单的题,其实很难,只是我们没有看清它的本质而已
今天我就带大家一起探索A + B Problem的秘密
## 第一种:常规做法
```c++
#include<iostream>
using namespace std;
int a,b,c;
int main(){
cin>>a>>b;
c=a+b;
cout<<c;
return 0;
}
```
这就是最朴素的做法,如果想让它变得快或短,你可以这样写
最短:
```c++
#include<iostream>
main(){int a,b;std::cin>>a>>b;std::cout<<a+b;}
```
最快:
```c++
#include<cstdio>
int read(){
char c=getchar();
int f=1,x=0;
while(c<'0'||c>'9'){
if(c=='-')
f=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
x=(x<<3)+(x<<1)+(c^48);
c=getchar();
}
return x*f;
}
void write(int x){
if(x<0){
putchar('-');
x=-x;
}
if(x>9)
write(x/10);
putchar(x%10+'0');
}
main(){
write(read()+read());
}
```
其实就是就是加了一个快读快写
## 第二种:高精度
如果A+B的值太大怎么办?那就用高精度吧,给大家看看我的代码
```c++
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
int a[10000010],b[10000010],c[10000011],f1,f2;
char s1[10000010],s2[10000010];
void jia(){
int k=max(a[0],b[0]),x;
for(int i=1;i<=k;i++){
c[i]+=a[i]+b[i];
x=c[i]/10;
c[i+1]+=x;
c[i]%=10;
}
if(c[k+1]>0)
c[0]=k+1;
else
c[0]=k;
if(f1==1&&f2==0&&c[k]!=0)
cout<<'-';
for(int i=c[0];i>=1;i--)
cout<<c[i];
}
void jian(){
int k=a[0];
for(int i=1;i<=k;i++){
c[i]+=a[i]-b[i];
if(c[i]<0){
c[i+1]--;
c[i]+=10;
}
}
while(c[k]==0&&k>1)
k--;
c[0]=k;
if(f1==1&&f2==1)
cout<<'-';
for(int i=c[0];i>=1;i--)
cout<<c[i];
}
int main(){
cin>>s1>>s2;
a[0]=strlen(s1);
b[0]=strlen(s2);
if(s1[0]=='-'){
f1=1;
for(int i=0;i<a[0];i++)
s1[i]=s1[i+1];
a[0]--;
}
if(s2[0]=='-'){
f2=1;
for(int i=0;i<b[0];i++)
s2[i]=s2[i+1];
b[0]--;
}
if(a[0]<b[0]||a[0]==b[0]&&s1<s2){
swap(s1,s2);
swap(f1,f2);
swap(a[0],b[0]);
}
for(int i=1;i<=a[0];i++)
a[i]=s1[a[0]-i]-'0';
for(int i=1;i<=b[0];i++)
b[i]=s2[b[0]-i]-'0';
if(f1==f2)
jia();
else
jian();
return 0;
}
```
很简单的一个高精度
## 第三种:随机数
```c++
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(){
int a;
srand((unsigned)time(NULL));
a=rand();
cout<<a;
return 0;
}
```
这是纯随机数
```c++
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b;
while(c!=a+b){
srand((unsigned)time(NULL));
c=rand();
}
cout<<c;
return 0;
}
```
这是一个看脸的随机数,很容易超时,我们来优化一下
```c++
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(){
int a,b,c,mod;
cin>>a>>b;
if(a+b<0){
a=-a;
b=-b;
cout<<'-';
}
mod=a+b+1;
while(c!=a+b){
srand((unsigned)time(NULL));
c=rand()%mod;
}
cout<<c;
return 0;
}
```
这个就好很多了,但还是很容易超时,这是随机数无法避免的
## 第四种:二分答案
```c++
#include<iostream>
using namespace std;
int a,b,l=-999999999,r=999999999;
int main(){
cin>>a>>b;
while(l<r){
int mid=(l+r)/2;
if(mid<a+b)
l=mid+1;
else
r=mid;
}
cout<<l;
return 0;
}
```
很简单的一个二分答案,运用二分思想
这篇博客以后会经常维护,想看更多方法的可以告诉我
对了,虽然A + B Problem是一道水题,但复制也要告诉我一声
这就是这篇博客的全部内容了,喜欢就点个赞吧