I have seen many problems that deals with big integers.
I use C++ and it can handle only some digits.
Can you help me on how to represent and use them?
I use C++ and it can handle only some digits.
Can you help me on how to represent and use them?
struct bignum{
int n; //number of digits
char digits[MAX];
};
'5'+'3'?#include <iostream>
#include <string.h>
using namespace std;
struct bignums{
int n;
char digits[200];
};
void init(bignums a, int def) //transfer the digits of the smallest number so they will be under the digits of the biggest number
{
a.n+=def;
for (int i=a.n-1;i>=0;i--)
{
a.digits[i+def]=a.digits[i];
a.digits[i]='0';
}
}
void addition(bignums a, bignums b, bignums c)
{
int carry=0,temp,z=1;
if (a.n-b.n>0)
init(b,a.n-b.n);
if (b.n-a.n>0)
init(a,b.n-a.n);
for (int i=a.n-1;i>=0;i--)
{
temp=(a.digits[i]-'0')+(b.digits[i]-'0')+carry;
c.digits[i+1]=(temp % 10)+'0';
carry=temp/10;
}
if (carry!=0)
c.digits[0]=carry+'0';
if (carry==0)
while(c.digits[z]!='0')
c.digits[z-1]=c.digits[z];
}
int main()
{
bignums a,b,c;
cin >> a.digits >> b.digits;
a.n=strlen(a.digits);
b.n=strlen(b.digits);
addition(a,b,c);
for (int i=0;i<c.n;i++)
cout << c.digits[i];
return 0;
}
void addition(bignums a, bignums b, bignums c)
{
int carry=0,temp,z=1;
if (a.n-b.n>0)
init(b,a.n-b.n);
if (b.n-a.n>0)
init(a,b.n-a.n);
for (int i=a.n-1;i>=0;i--)
{
temp=(a.digits[i]-'0')+(b.digits[i]-'0')+carry;
c.digits[i+1]=(temp % 10)+'0';
carry=temp/10;
}
if (carry!=0)
c.digits[0]=carry+'0';
if (carry==0)
while(c.digits[z]!='0')
{
c.digits[z-1]=c.digits[z];
z++;
}
}
#include <iostream>
#include <string.h>
using namespace std;
struct bignums
{
int n;
char digits[200];
};
void init( bignums& a, int def )
{
a.n+=def;
for (int i=a.n-1;i>=0;i--)
{
a.digits[i+def]=a.digits[i];
a.digits[i]='0';
}
}
void addition(bignums a, bignums b, bignums& c)
{
int carry=0,temp,z=1;
if (a.n-b.n>0)
init(b,a.n-b.n);
if (b.n-a.n>0)
init(a,b.n-a.n);
for (int i=a.n-1;i>=0;i--)
{
temp=(a.digits[i]-'0')+(b.digits[i]-'0')+carry;
c.digits[i+1]=(temp % 10)+'0';
carry=temp/10;
}
if (carry!=0)
{
c.digits[0]=carry+'0';
c.n = a.n + 1;
}
if (carry==0)
while( z <= a.n )
{
c.digits[z-1]=c.digits[z];
c.n = a.n;
z++;
}
}
int main()
{
bignums a,b,c;
cin >> a.digits >> b.digits;
a.n=strlen(a.digits);
b.n=strlen(b.digits);
addition(a,b,c);
for (int i=0;i<c.n;i++)
cout << c.digits[i];
cout << endl;
return 0;
}