#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() ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgoKc3RydWN0IGJpbmFyeQp7CiAgICB2b2lkIGRpc3BsYXkoKSBjb25zdCB7IGZvciggaW50IGQgOiBkaWdpdHMgKSBzdGQ6OmNvdXQgPDwgZCA7IHN0ZDo6Y291dCA8PCAnXG4nIDsgfQogICAgYmluYXJ5IG9wZXJhdG9yKyAoIGNvb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