Post date: Jan 18, 2014 10:29:11 PM
Problem
{Ques.. Sum of nos. nos. like(very very long no.s)
A=123456278798238093532765432662476427646456353425635454854
B=1234562787982380935327654326624764276464563534248758758756
C=123456278798238093532765432662476427646456353425634436746432}
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Calc sum of long numbers
Created Date : 19-01-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string CalcLongNumsSum(string n1, string n2)
{
string result;
int carry(0);
if (n1.empty() || n2.empty()){
return n1 + n2;
}
reverse(n1.begin(), n1.end());
reverse(n2.begin(), n2.end());
int len = n1.size() > n2.size() ? n1.size() : n2.size();
for (int i = 0; i < len; ++i){
int d1 = (i < n1.size()) ? n1[i] - '0' : 0;
int d2 = (i < n2.size()) ? n2[i] - '0' : 0;
result.push_back((d1 + d2 + carry) % 10 + '0');
carry = (carry + d1 + d2) / 10;
}
if (carry > 0){
result.push_back(carry + '0');
}
reverse(result.begin(), result.end());
return result;
}
void DoTest(string n1, string n2)
{
string result = CalcLongNumsSum(n1, n2);
cout << string(1 + result.size() - n1.size(), ' ') << n1 << endl;
cout << '+' << string(result.size() - n2.size(), ' ') << n2 << endl;
cout << '=' << result << endl;
cout << endl;
}
int main()
{
DoTest("123", "");
DoTest("123", "99");
DoTest("12334343454521", "9987237868642");
return 0;
}
Output
123
+
=123
123
+ 99
=222
12334343454521
+ 9987237868642
=22321581323163
Press any key to continue . . .