C++ A+B Problem

A+B Problem - 洛谷

如何用C++实现A+B问题?

方法1:

最简单的直接输入整数A与B,用变量C储存其和并输出。

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

洛谷提交完,不用O2优化耗时34ms。

方法2:

有没有更快的方法?cin和cout处理比scanf、printf慢。

#include <bits/stdc++.h>
using namespace std;
int main(){
	int a=0,b=0;
	scanf("%d%d",&a,&b);
	int c=a+b;
	printf("%d",c);
return 0;
}

洛谷提交完,不用O2优化耗时33ms,快了1ms。

方法3:

getchar、putchar比scanf、printf都要快,那就用它们来一位一位输出。

#include <bits/stdc++.h>
using namespace std;
inline int read(){
	int x=0,f=1;
	char ch=getchar(); 
	while(ch<'0'||ch>'9'){
		if(ch=='-')f=-1;
		ch=getchar();
	}
    while(ch>='0'&&ch<='9'){
		x=x*10+ch-'0';
		ch=getchar();
	}
return x*f;
}
void write(int x){
	if(x<0)x=-x,putchar('-');
	if(x>9)write(x/10);
	putchar(x%10+'0');
}
int main(){
	write(read()+read());
return 0;
}

洛谷提交完,不用O2优化耗时30ms,又快了3ms。

这里涉及到了快读快写,当然还有更快的方法,本人就只会这些了。

欢迎来洛谷联系我。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值