Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two strings mathematically?

i was looking around the forums and i still couldnt find my answer to my problem. I got two strings, that are just really an array of numbers. for example(i just choose random numbers

    string input1="12345678909876543212";
    string input2="12345";

I want to add these two string together but act them like there integers. My goal is creating a class where i can add bigger numbers than (long long int) so it can exceed the largest long long int variable.

So i revese the string with no problem, so now there

  input1="21234567890987654321" 
  input2="54321"

then i tried adding, let's say input1[0]+input2[0] (2+5) to a new string lets call it newString[0] where that would equal (7); but i cant find a good way to temporally convert the current number in the string so i can add it to the new string? can anyone help. I get sick and tired of atoi,stof,stod. they don't seem to work at all for me. Any way i can make this function work. I don't care about making the class yet, i just care about finding a way to add those two strings mathematically but still maintaining the newString's string format. Thank you for whoever can figure this out for me

like image 461
OPJ Avatar asked Feb 15 '23 01:02

OPJ


2 Answers

Okay, so, assuming your only problem is with the logic, not the class design thing, I came up with this logic

  • fill up the inputs with 0s, checking the lengths, match the lengths
  • add like normal addition, keeping track of carry
  • finally remove leading zeros from result

So using std::transform with a lambda function on reverse iterators :-

char carry = 0;

std::transform(input1.rbegin(),input1.rend(),input2.rbegin(),
              result.rbegin(),[&carry]( char x,  char y){
    char z = (x-'0')+(y-'0') + carry;
    if (z > 9)
    {
        carry = 1;
        z -= 10;
    }
    else
    {
        carry = 0;
    }
    return z + '0';
});

//And finally the last carry
result[0] = carry + '0';

//Remove the leading zero
n = result.find_first_not_of("0");
if (n != string::npos)
{
    result = result.substr(n);
}

See Here

Edit "Can you comment on what your doing here"

                +--------+--------------+------------+-------> Reverse Iterator
                |        |              |            |
std::transform( | input1.rbegin(), input1.rend(),input2.rbegin(),
               result.rbegin(), [&carry]( char x,  char y){
               //This starts a lambda function
    char z = (x-'0')+(y-'0') + carry; // x,y have ASCII value of each digit
    // Substracr ASCII of 0 i.e. 48 to get the "original" number
    // Add them up
    if (z > 9) //If result greater than 9, you have a carry
    {
        carry = 1; // store carry for proceeding sums
        z -= 10; // Obviously 
    }
    else
    {
        carry = 0; //Else no carry was generated
    }
    return z + '0'; // Now you have "correct" number, make it a char, add 48
});

std::transform is present in header <algorithm>, see the ideone posted link.

like image 198
P0W Avatar answered Feb 17 '23 15:02

P0W


Here's A Solution for adding two numbers represented as strings .

#include<iostream>
using namespace std;

string add(string a, string b)
{
   int al=a.size()-1;
   int bl=b.size()-1;

   int carry=0;
   string result="";

   while(al>=0 && bl>=0)
    {
    int temp = (int)(a[al] - '0') + (int)(b[bl] - '0') + carry ;
    carry = 0;
    if(temp > 9 )
    {
        carry=1;
        temp=temp-10;
    }

    result+=char(temp + '0');
    al--;
    bl--;
    }

   while(al>=0)
    {
        int temp = (int)(a[al] - '0') + carry ;
        carry = 0;
        if(temp>9)
        {
            carry=1;
            temp=temp%10;
        }

        result+=char(temp + '0');
        al--;
    }

   while(bl>=0)
    {
        int temp = (int)(b[bl] - '0') + carry ;
        carry = 0;
        if(temp>9)
        {
            carry=1;
            temp=temp%10;
        }

        result+=char(temp + '0');
        bl--;
    }

if(carry)
    result+="1";

string addition="";

for(int i=result.size()-1;i>=0;i--)
    addition+=result[i];   // reversing the answer

return addition;
}

string trim(string a)   // for removing leading 0s
{
   string res="";
   int i=0;

   while(a[i]=='0')
      i++;

   for(;i<a.size();i++)
    res+=a[i];

   return res;
}


int main()
{
    string a;
    string b;

    cin>>a>>b;

    cout<<trim(add(a,b))<<endl;
}
like image 41
Nikhilesh Gautam Avatar answered Feb 17 '23 15:02

Nikhilesh Gautam