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:
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?
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;
}
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?
Comment