Subtraction of strings in C++

Subtraction of strings in C++

Written by Alan on Jun 27th, 2021 Views Report Post

Hello!

I'm Alan, a dev with experience in Javascript, Python, and some c++. I've never been on this platform before, so I'm open to all feedback.

Let's get started!

Imagine you want to subtract 2 very long numbers in C++. Just like any other normal language like python or Javascript, you try to just use the minus sign. But you get this super annoying error: integer constant is too large for its type You try to use unsigned long long's and all the other data types, but it doesn't work. Unlike other languages, C++ has an integer limit, which is 2147483647

Now, how do we solve this? The simplest way is to use a lib- but if you can't do that, use a string. Strings are almost infinite in length, therefore you can use them to store large "numbers".

To subtract 2 numbers, you subtract each digit individually and carry over the borrows. This is the same case in programming. You just loop through the reversed string!

Padding numbers

First, we need to make sure both of our numbers are the same length. To do this, we pad them with 0's. We can create a simple function for this:

string makeThemSameLength(string s1, int n) {
    for (int i = 0; i < n; i++)
    {
        s1 = '0' + s1;
    }
    return s1;
}

This will add N 0's in front of the number. We will calculate N later.

Subtracting digits

Next, we need to be able to subtract single digits and return the borrowed and digits. To do this, we need to declare a structure.

struct SubDigResult
{
    int r;
    int b;
};

In this structure, r is the result and b is borrow. Let's implement the function. We want this function to take in 3 chars and return a SubDigResult. Hence, we have this:

struct SubDigResult subDigits(char c1, char c2, int b) {}

Let's fill it in with code! We first want to make both chars an integer.

int i1 = c1 - '0';
int i2 = c2 - '0';

Then, we want to subtract them. Here, we also want to subtract the borrowed number, if any.

// n is the number, or result
int n = i1 - i2 - b;

Now, let's assign the values to the structure.

if (n >= 0) {
    res.r = n;
    res.b = 0;
} else {
    res.r = n+10;
    res.b = 1;
}

We want to check if we need to borrow, which is done by checking if n is greater than 0. Together, we now have

struct SubDigResult subDigits(char c1, char c2, int b) {
    struct SubDigResult res;
    int i1 = c1 - '0';
    int i2 = c2 - '0';
    int n = i1 - i2 - b;
    if (n >= 0) {
        res.r = n;
        res.b = 0;
    } else {
        res.r = n+10;
        res.b = 1;
    }
    return res;
}

Subtracting the strings!

Now, let's get to the fun part! As mentioned at the beginning, we want to subtract both numbers by looping through their digits. Let's create a final subNums function for this. It will take in 2 strings to subtract, and return a string.

string subNums(string s1, string s2) {}

We will need a borrow and a result variable to return later.

int borrow = 0;
string res;

Now, let's loop through the string in reverse.

for (int i = s1.length()-1; i >= 0; i--) {}

Inside here, we want to subtract each digit, then get the borrow from it and append it to the result!

struct SubDigResult t = subDigits(s1[i], s2[i], borrow);
borrow = t.b;
res = char ('0' + t.r) + res;

This is the result:

string subNums(string s1, string s2) {
    int borrow = 0;
    string res;
    for (int i = s1.length()-1; i >= 0; i--)
    {
        struct SubDigResult t = subDigits(s1[i], s2[i], borrow);
        borrow = t.b;
        res = char ('0' + t.r) + res;
    }
    return res;
}

Let's put it together!

int main()
{
    int first, second;
    cin >> first, second;
    cout << subNums(first, second) << endl;
    return 0;
}

This works, but sometimes our padded zeros are still there... Let's fix that!

string stripLeadingZero(string s) {
    string new_s = s;
    for (int i = 0; i < s.length(); i++)
    {
        if (s[i] == '0') {
            new_s = new_s.substr(1);
        }
        else break;
    }
    return new_s;
}

This will strip all the zeros until a nonzero digit is reached.

Let's edit our code to include that:

int main()
{
    int first, second;
    cin >> first, second;
    cout << stripLeadingZero(subNums(first, second)) << endl;
    return 0;
}

Thanks for tuning in!

Now, we have a fully working subtraction code for strings in C++. If you have any questions, feel free to ask them in the comments.

As this is my first post, please post any suggestions or places I could improve on. I'm always open to feedback!

Comments (0)