In: Computer Science
CS 211
Q.Adding BIG Integers In C++ an int is in the range 0 to 65535. But what if we need to add larger integers? Say we want to compute the sum 2345566777844567+ 9999988777765768009998. Your task in this assignment is to make this happen. Write a function string add(string a, string b)
Hi, Please find the solution, Explanations are inline.
//
// main.cpp
// HugeNumbersAdd
//
#include <iostream>
#include "string"
#include "algorithm"
using namespace std;
string add(string a, string b){
if(a.length()>b.length()){
string temp = a;
a=b;
b=temp;
}
string res = "";//empty for result
int len1 = a.length();
int len2 = b.length();
reverse(a.begin(), a.end());
reverse(b.begin(),b.end());
int carry = 0;
for (int i=0; i<len1; i++) {//adding until the size of the lower number
int sum = ((a[i]-'0')+(b[i]-'0')+carry);//-'0' is to convert char to number
res.push_back(sum%10+'0');
//carry for next step
carry = sum/10;
}
for(int i=len1;i<len2;i++){//this loop is after we are done with addition and if carry remains
int sum = ((b[i]-'0')+carry);
res.push_back(sum%10+'0');
carry = sum/10;
}
if(carry){//finally if carry remains
res.push_back(carry+'0');
}
reverse(res.begin(), res.end());//finally reversing
return res;
}
int main(int argc, const char * argv[]) {
string str1="122325",str2="45468";
cout<<"Enter big number 1:";
cin>>str1;
cout<<endl<<"Enter big number 2:";
cin>>str2;
cout<<add(str1, str2)<<endl;
}