Post date: Oct 26, 2013 1:46:39 AM
Problem
You have two integer arrays.
Treat these arrays as if they were big numbers, with one digit in each slot.
Perform addition on these two arrays and store the results in a new array.
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Compute sum of two digit arrays
Created Date : 26-10-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void ComputeSum(vector<int>& in1, vector<int>& in2, vector<int>& out)
{
int carry = 0;
if(in1.size() < in2.size()) swap(in1, in2);
for(int i = 0; i < in2.size(); ++i){
out.push_back((carry + in1[i] + in2[i]) % 10);
carry = (carry + in1[i] + in2[i]) / 10;
}
for(int i = in2.size(); i < in1.size(); ++i){
out.push_back((carry + in1[i]) % 10);
carry = (carry + in1[i]) / 10;
}
if(carry) out.push_back(carry);
}
void DoTest(vector<int>& in1, vector<int>&in2)
{
cout << "Input 1:" << endl;
for(auto i: in1){
cout << setw(4) << i;
}
cout << "\nInput 2: " << endl;
for(auto i: in2){
cout << setw(4) << i;
}
vector<int> out;
ComputeSum(in1, in2, out);
cout << "\nOutput: " << endl;
for(auto i: out){
cout << setw(4) << i;
}
cout << "\n-----------------------" << endl;
}
int main()
{
int arr0[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int arr1[] = {9, 8, 3, 4, 5, 6, 7};
vector<int> in1(arr0, arr0 + sizeof(arr0) /sizeof(arr0[0]));
vector<int> in2(arr1, arr1 + sizeof(arr1) /sizeof(arr1[0]));
DoTest(in1, in2);
int arr2[] = {1, 2, 3, 4, 5, 6, 9, 9, 9};
int arr3[] = {9, 8, 3, 4, 5, 6, 7};
vector<int> in3(arr2, arr2 + sizeof(arr2) /sizeof(arr2[0]));
vector<int> in4(arr3, arr3 + sizeof(arr3) /sizeof(arr3[0]));
DoTest(in4, in3);
return 0;
}
Output
Input 1:
1 2 3 4 5 6 7 8 9
Input 2:
9 8 3 4 5 6 7
Output:
0 1 7 8 0 3 5 9 9
-----------------------
Input 1:
9 8 3 4 5 6 7
Input 2:
1 2 3 4 5 6 9 9 9
Output:
0 1 7 8 0 3 7 0 0 1
-----------------------
Press any key to continue . . .