465 - Overflow

题意:处理两个大整数,判断有哪些数超出了int的取值范围

注意事项:

①使用istringstream()需要调用#include <sstream>函数

用法:istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。

②int最大值为0x7fffffff,两个ff组成一个字节,恰好为四个字节


#include <iostream>
#include <string>
#include <sstream>//使用istringstream()需要调入的头文件

using namespace std;

string getMaxStr()
{
	int n=0x7fffffff;
	string s="";
	while(n!=0)
	{
		s=(char)(n%10+'0')+s;
		n=n/10;
	}
	return s;
}

bool cmp(const string &a,const string &b)
{
	int alen=a.size();
	int blen=b.size();
	if(alen==blen)
	{
		for(int i=0;i<alen;i++)
			if(a[i]!=b[i])
				return a[i]>b[i];
	}
	else
	{
		return alen>blen;
	}
	return false;
}

int main()
{
	string a,op,b;
	string max_str=getMaxStr();
	while(cin>>a>>op>>b)
	{
		bool over=false;
		cout<<a<<" "<<op<<" "<<b<<endl;
		while(a.size()>1 && a[0]=='0')//###,wa n多次,大整数问题记着清除前置零,判断为‘0’而不是0.
			a.erase(0,1);
		while(b.size()>1 && b[0]=='0')
			b.erase(0,1);
		if(cmp(a,max_str))
		{
			cout<<"first number too big"<<endl;
			over=true;
		}
		if(cmp(b,max_str))
		{
			cout<<"second number too big"<<endl;
			over=true;
		}
		if(over)
		{
			if(op=="+")
				cout<<"result too big"<<endl;
			else if(op=="*" && a!="0" && b!="0")
				cout<<"result too big"<<endl;
		}
		else
		{
			long long aa,bb,cc;
			istringstream(a)>>aa;
			istringstream(b)>>bb;
			if(op=="+")
				cc=aa+bb;
			else if(op=="*")
				cc=aa*bb;
			if(cc>0x7fffffff)
				cout<<"result too big"<<endl;
		}
	}
	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值