Difference of two large numbers

Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find difference of these two numbers.

Examples:

Input : str1 = "11443333311111111100", 
        str2 =     "1144422222221111"
Output : 11442188888888889989

Input :str1 = "122387876566565674",
       str2 =     "31435454654554"
Output : 122356441111911120

This is simple based on school mathematics. We traverse both strings from end, one by one subtract digits.
1) Reverse both strings.
2) Keep subtracting digits one by one from 0’th index (in reversed strings) to end of smaller string, append the diff if it’s positive to end of result. If difference(diff) is negative then add 10 and keep track of carry as 1 if it’s positive then carry is 0.
3) Finally reverse the result.

// C++ program to find difference of two large numbers.
#include<bits/stdc++.h>
using namespace std;
// Returns true if str1 is smaller than str2.
bool isSmaller(string str1, string str2)
{
    // Calculate lengths of both string
    int n1 = str1.length(), n2 = str2.length();
    if (n1 < n2)
       return true;
    if (n2 < n1)
       return false;
    for (int i=0; i<n1; i++)
       if (str1[i] < str2[i])
          return true;
       else if (str1[i] > str2[i])
          return false;
    return false;
}
// Function for find difference of larger numbers
string findDiff(string str1, string str2)
{
    // Before proceeding further, make sure str1
    // is not smaller
    if (isSmaller(str1, str2))
        swap(str1, str2);
    // Take an empty string for storing result
    string str = "";
    // Calculate length of both string
    int n1 = str1.length(), n2 = str2.length();
    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());
    int carry = 0;
    // Run loop till small string length
    // and subtract digit of str1 to str2
    for (int i=0; i<n2; i++)
    {
        // Do school mathematics, compute difference of
        // current digits
        int sub = ((str1[i]-'0')-(str2[i]-'0')-carry);
        // If subtraction is less then zero
        // we add then we add 10 into sub and
        // take carry as 1 for calculating next step
        if (sub < 0)
        {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
        str.push_back(sub + '0');
    }
    // subtract remaining digits of larger number
    for (int i=n2; i<n1; i++)
    {
        int sub = ((str1[i]-'0') - carry);
        carry = 0;
        str.push_back(sub + '0');
    }
    // reverse resultant string
    reverse(str.begin(), str.end());
    return str;
}
// Driver code
int main()
{
    string str1 = "12";
    string str2 = "198111";
    cout << findDiff(str1, str2);
    return 0;
}

Output:

198099

 

Optimized solution
We can avoid the first two string reverse operations by traversing them from end. Below is optimized solution.

// C++ program to find difference of two large numbers.
#include<bits/stdc++.h>
using namespace std;
// Returns true if str1 is smaller than str2,
// else false.
bool isSmaller(string str1, string str2)
{
    // Calculate lengths of both string
    int n1 = str1.length(), n2 = str2.length();
    if (n1 < n2)
        return true;
    if (n2 > n1)
        return false;
    for (int i=0; i<n1; i++)
    {
        if (str1[i] < str2[i])
            return true;
        else if (str1[i] > str2[i])
            return false;
    }
    return false;
}
// Function for finding difference of larger numbers
string findDiff(string str1, string str2)
{
    // Before proceeding further, make sure str1
    // is not smaller
    if (isSmaller(str1, str2))
        swap(str1, str2);
    // Take an empty string for storing result
    string str = "";
    // Calculate lengths of both string
    int n1 = str1.length(), n2 = str2.length();
    int diff = n1 - n2;
    // Initially take carry zero
    int carry = 0;
    // Traverse from end of both strings
    for (int i=n2-1; i>=0; i--)
    {
        // Do school mathematics, compute difference of
        // current digits and carry
        int sub = ((str1[i+diff]-'0') -
                   (str2[i]-'0') -
                   carry);
        if (sub < 0)
        {
            sub = sub+10;
            carry = 1;
        }
        else
            carry = 0;
        str.push_back(sub + '0');
    }
    // subtract remaining digits of str1[]
    for (int i=n1-n2-1; i>=0; i--)
    {
        if (str1[i]=='0' && carry)
        {
            str.push_back('9');
            continue;
        }
        int sub = ((str1[i]-'0') - carry);
        if (i>0 || sub>0) // remove preceding 0's
            str.push_back(sub+'0');
        carry = 0;
    }
    // reverse resultant string
    reverse(str.begin(), str.end());
    return str;
}
// Driver code
int main()
{
    string str1 = "88";
    string str2 = "1079";
    cout << findDiff(str1, str2);
    return 0;
}

Output:

991

Time complexity : O(n1 + n2)

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/difference-of-two-large-numbers/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

 

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar