1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| string add(string s1, string s2) { string int1 = s1.substr(0, s1.find('.')), int2 = s2.substr(0, s2.find('.')); string frac1 = s1.substr(s1.find('.') + 1), frac2 = s2.substr(s2.find('.') + 1);
if (int1.size() < int2.size()) int1 = string(int2.size() - int1.size(), '0') + int1; else int2 = string(int1.size() - int2.size(), '0') + int2; if (frac1.size() < frac2.size()) frac1 = frac1 + string(frac2.size() - frac1.size(), ' '); else frac2 = frac2 + string(frac1.size() - frac2.size(), ' ');
int carry = 0; string fraction = string(frac1.size(), ' '); for (int i = fraction.size() - 1; i >= 0; --i) { int cur = frac1[i] - '0' + frac2[i] - '0' + carry; carry = cur / 10; fraction[i] = cur % 10 + '0'; } string integer = string(int1.size(), ' '); for (int i = integer.size() - 1; i >= 0; --i) { int cur = int1[i] - '0' + int2[i] - '0' + carry; carry = cur / 10; integer[i] = cur % 10 + '0'; } if (carry == 1) return '1' + integer + '.' + fraction; else return integer + '.' + fraction; }
|