I've done my code for addition using string.
I'd really happy if you guys can guide me with the optimization. It's not really necessary but if you are interested.
string add (string a, string b) {
string str;
string temp;
short carry = 0;
short result = 0;
bool c_sign = 0;
long l = 0;
// padding 0 to decimal part
l = ( a.size()-a.find(".") ) - ( b.size()-b.find(".") );
if (l > 0) b.resize(b.size() + l, '0');
if (l < 0) a.resize(a.size() - l, '0');
// padding 0 to integer part
l = a.size()-b.size();
if (l > 0) b.insert(1, l, '0');
if (l < 0) a.insert(1, -l, '0');
// covert sign to digit, convert number to 9's complement
if (a[0] == '-') { a[0]='0'; a = complement(a); carry++; } else a[0]='0';
if (b[0] == '-') { b[0]='0'; b = complement(b); carry++; } else b[0]='0';
// this will be the carry if the result is negative
// the actual process requires you to subtract 1 from the result
// using this the program will only calculate with carry 1 less than current
c_sign = ( carry==2 ? 1:0 );
// adding
for (long i=a.size()-1; i>=0; i--) {
if (a[i] == '.') {
str += '.';
continue;
}
result = a[i] + b[i] + carry - '0' - '0';
carry = result/10;
result %= 10;
str += result + '0';
}
// reverse the result, since the addition was (*must) done from back
for (long i=str.size()-1; i>=0; i--) temp += str[i];
str = temp;
// signing
if (str[0] < '5') str = "+" + temp;
else { // redo adding
carry = c_sign;
str.clear();
temp.clear();
for (long i=a.size()-1; i>=0; i--) {
if (a[i] == '.') {
str += '.';
continue;
}
result = a[i] + b[i] + carry - '0' - '0';
carry = result/10;
result %= 10;
str += result + '0';
}
for (long i=str.size()-1; i>=0; i--) temp += str[i];
str = "+" + temp;
str = complement(str);
}
return compact(str);
}