Math with strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TedBronson
    New Member
    • Apr 2013
    • 1

    Math with strings

    Hello,

    I am trying to make a function which takes two very large integers inside of strings, subtracts them, and returns the result as a string.

    One goal is to do this without using third-party libraries, so please don't tell me to use Boost, MathTT etc.

    I was able to make a function which adds 1 to a string:

    [CODE=cpp]void IncrementString (string& s)
    {
    string::reverse _iterator i = s.rbegin(), end = s.rend();
    int carryOver = 1;
    while (carryOver && i != end)
    {
    int val = (*i - '0') + carryOver;
    carryOver = (val / 10);
    *i = '0' + (val % 10);
    ++i;
    }
    if (carryOver)
    s.insert(0, "1");
    }[/CODE]

    But my code to subtract strings doesn't work:

    Code:
    string StringSubtract(string& y, string& z) {
        string::reverse_iterator i = z.rbegin(), iend = z.rend();
        string::reverse_iterator j = y.rbegin(), jend = y.rend();
        string answer;
        bool borrow = false;
        while (j != jend) {
            int p, q;
            p = *i - '0';
            q = *j - '0';
            if (borrow) {
                p--;
                borrow = false;
            }
            if (q > p) {
                borrow = true;
                p += 10;
            }
            int r = p - q;
            answer = answer.insert(0,to_string(r)); //PROBLEM!
            i++;
            j++;
        }
        while (i != iend) {
            if (borrow) {
                *i--;
                borrow = false;
            }
            const char* s = *i;
            answer = answer.insert(0,&s);
        }
        return answer;
    }
    The error I get is with the string.insert() function - invalid conversion from char to const char*.

    I've tried sprintf(), string_to() and using a char, nothing seems to work! Is there any other way to put an integer in the front of a string that is not a constant?
    Last edited by TedBronson; Apr 26 '13, 12:28 AM. Reason: typos
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    What do you mean by "very large integers"?

    Using strings and iterators will be very very slow.

    Instead consider an array of unsigned int that you create on the heap. Now you can work at the binary bit level so your addition and subtraction is very straightforward . An array is guaranteed contiguous allowing you to scan bit-by-bit the entire array.

    You can aleays write a function to convert your array to a basic_string<ch ar> (aka a string object).

    Comment

    Working...