标签:for max big stream sum ble 而且 cst 字符串
这一题实在有坑,而且是大坑,本来以为只是简单的整数题,最多用long就可以了吧,但是实际上这一题要用到大整数加法,在c++中大整数加法是通过字符串模拟来实现的,Java可以直接使用BigInteger类,后面贴代码,下面是c++常用数据类型的范围:
short : -32768 ~ 32767
int : -2147483648 ~ 2147483647
long : -2147483468 ~ 2147483647
float : 1.17549e-038 ~ 3.40282e+038
double : 2.22507e-308 ~ 1.79769e+308
c++实现大数加法:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int i = 0;
int m[10000] , n[10000] , sum[20000];
string a , b;
int count;
cin >> count;
int flag = 1;
while(count--)
{
cin >> a;
cin >> b;
memset(m , 0 , sizeof(m));
memset(n , 0 , sizeof(n));
memset(sum , 0 , sizeof(sum));
int pre = 0;
int lena = a.length();
int lenb = b.length();
int lenmax = max(lena , lenb);
for(i = 0 ; i < lena ; i++)
m[lena - i - 1] = a[i] - ‘0‘;
for(i = 0 ; i < lenb ; i++)
n[lenb - i - 1] = b[i] - ‘0‘;
for(i = 0 ; i < lenmax ; i++)
{
sum[i] += m[i] + n[i] + pre / 10;
pre = sum[i];
}
while(pre > 9)
{
sum[lenmax] = pre / 10 % 10;
lenmax++;
pre = pre / 10;
}
cout << "Case " << flag << ":" << endl;
flag++;
cout << a << " + " << b << " = ";
for(i = lenmax - 1 ; i >= 0 ; i--)
cout << sum[i] % 10;
cout << endl;
if(count)
cout << endl;
}
return 0;
}
还需要注意的一点是,在hdu提交答案的过程中,一定要注意不要多打空格。
标签:for max big stream sum ble 而且 cst 字符串
原文地址:https://www.cnblogs.com/zzb-algorithm/p/11794856.html