C++11大数加减
# include "pch.h"
# include <iostream>
# include <algorithm>
# include <string>
# include <vector>
using namespace std;
class BigInt
{
public :
BigInt ( string str) : strDigit ( str) { }
private :
string strDigit;
friend ostream& operator << ( ostream & out, const BigInt & src) ;
friend BigInt operator + ( const BigInt & lhs, const BigInt & rhs) ;
friend BigInt operator - ( const BigInt & lhs, const BigInt & rhs) ;
} ;
ostream& operator << ( ostream & out, const BigInt & src)
{
out << src. strDigit;
return out;
}
BigInt operator + ( const BigInt & lhs, const BigInt & rhs)
{
string result;
bool flag = false ;
int size1 = lhs. strDigit. length ( ) - 1 ;
int size2 = rhs. strDigit. length ( ) - 1 ;
int i = size1, j = size2;
for ( ; i >= 0 && j >= 0 ; -- i, -- j)
{
int ret = lhs. strDigit[ i] - '0' + rhs. strDigit[ j] - '0' ;
if ( flag)
{
ret += 1 ;
flag = false ;
}
if ( ret >= 10 )
{
ret %= 10 ;
flag = true ;
}
result. push_back ( ret + '0' ) ;
}
if ( i >= 0 )
{
while ( i >= 0 )
{
int ret = lhs. strDigit[ i] - '0' ;
if ( flag)
{
ret += 1 ;
flag = false ;
}
if ( ret >= 10 )
{
ret %= 10 ;
flag = true ;
}
result. push_back ( ret + '0' ) ;
i-- ;
}
}
else if ( j >= 0 )
{
while ( j >= 0 )
{
int ret = rhs. strDigit[ j] - '0' ;
if ( flag)
{
ret += 1 ;
flag = false ;
}
if ( ret >= 10 )
{
ret %= 10 ;
flag = true ;
}
result. push_back ( ret + '0' ) ;
j-- ;
}
}
if ( flag)
{
result. push_back ( '1' ) ;
}
reverse ( result. begin ( ) , result. end ( ) ) ;
return result;
}
BigInt operator - ( const BigInt & lhs, const BigInt & rhs)
{
string result;
bool flag = false ;
bool minor = false ;
string maxStr = lhs. strDigit;
string minStr = rhs. strDigit;
if ( maxStr. length ( ) < minStr. length ( ) )
{
maxStr = rhs. strDigit;
minStr = lhs. strDigit;
minor = true ;
}
else if ( maxStr. length ( ) == minStr. length ( ) )
{
if ( maxStr < minStr)
{
maxStr = rhs. strDigit;
minStr = lhs. strDigit;
minor = true ;
}
else if ( maxStr == minStr)
{
return string ( "0" ) ;
}
}
else
{
;
}
int size1 = maxStr. length ( ) - 1 ;
int size2 = minStr. length ( ) - 1 ;
int i = size1, j = size2;
for ( ; i >= 0 && j >= 0 ; -- i, -- j)
{
int ret = maxStr[ i] - minStr[ j] ;
if ( flag)
{
ret -= 1 ;
flag = false ;
}
if ( ret < 0 )
{
ret += 10 ;
flag = true ;
}
result. push_back ( ret + '0' ) ;
}
while ( i >= 0 )
{
int ret = maxStr[ i] - '0' ;
if ( flag)
{
ret -= 1 ;
flag = false ;
}
if ( ret < 0 )
{
ret += 10 ;
flag = true ;
}
result. push_back ( ret + '0' ) ;
i-- ;
}
if ( minor)
{
result. push_back ( '-' ) ;
}
reverse ( result. begin ( ) , result. end ( ) ) ;
return result;
}
int main ( )
{
BigInt int1 ( "9785645649886874535428765" ) ;
BigInt int2 ( "28937697857832167849697653231243" ) ;
BigInt int3 ( "9785645649886874535428765" ) ;
cout << int1 + int2 << endl;
cout << int1 - int2 << endl;
return 0 ;
}