1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
#include <vector>
#include <algorithm>
struct binary
{
void display() const { for( int d : digits ) std::cout << d ; std::cout << '\n' ; }
binary operator+ ( const binary& that ) const ;
/*private:*/ std::vector<int> digits ;
};
binary binary::operator+ ( const binary& that ) const
{
auto n = std::max( digits.size(), that.digits.size() ) ; // larger size
n += 1 ; // may overflow, so one more
std::vector<int> first( digits.rbegin(), digits.rend() ) ;
// first now contains the first set of digits in reverse order
first.resize(n) ; // make its size equal to the larger size (add zeroes at the end)
std::vector<int> second( that.digits.rbegin(), that.digits.rend() ) ;
// second now contains the second set of digits in reverse order
second.resize(n) ; // make its size equal to the larger size (add zeroes at the end)
binary result ;
result.digits.resize(n) ;
// simulate hand-addition with carry
// but left to right because digits are reversed
int carry = 0 ;
for( std::size_t i = 0 ; i < first.size() ; ++i ) // for each digit
{
int& d = result.digits[i] ;
d = first[i] + second[i] + carry ; // add the two digits, carry
// a digit must be either 0 or 1; so
if( d > 1 ) { carry = d / 2 ; d %= 2 ; } // adjust for overflow
else carry = 0 ;
}
// if the most significant (in reverse order) digit is zero, remove it
if( result.digits.back() == 0 ) result.digits.pop_back() ;
// reverse the digits of the result
std::reverse( result.digits.begin(), result.digits.end() ) ;
return result ;
}
int main()
{
const binary a { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } } ;
a.display() ;
const binary b { { 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } } ;
b.display() ;
const binary c = a + b ;
c.display() ;
}
|