c++ string (int) + string (int) -


this question has answer here:

i have 2 strings, both contain numbers. numbers bigger max of uint64_t.

how can still add these 2 numbers , convert result string?

well, can either use bigger datatype (for example library deals large integers), or can knock own.

i suggest if 1 off, long addition have learned in first few years of school. can operate directly on 2 strings, add columns, 'carry', , build string containing result. can without conversion or binary.

here. fun, knocked solution you:

string add( const string& a, const string& b ) {     // reserve storage result.     string result;     result.reserve( 1 + std::max(a.size(), b.size()) );      // column positions , carry flag.     int apos = a.size();     int bpos = b.size();     int carry = 0;      // add columns     while( carry > 0 || apos > 0 || bpos > 0 )     {         if( apos > 0 ) carry += a[--apos] - '0';         if( bpos > 0 ) carry += b[--bpos] - '0';         result.push_back('0' + (carry%10));         carry /= 10;     }      // result string backwards.  reverse , return it.     reverse( result.begin(), result.end() );     return result; } 

note that, clarity, code doesn't attempt handle errors. doesn't negatives, it's not hard fix that.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -