※ 引述《oin1104 (是oin的说)》之铭言:
: 题目:
: 给你字串
: -1/2+1/2
: 3/6-1/3+2/5-10/2
: 要你算出结果
: 思路:
: 机掰
: 超麻烦
: 直接做一个class num
: 然后用operator处理加减
: 生成num就暴力的一个一个字放进去
: 姆咪
我先parse 每个分数字串 跟 +-
再把分数转成一个struct做+-
做+-就是先通分加减完再约分
最后再转回字串
class Solution {
struct frac {
int numerator;
int denominator;
frac(string s){
auto pos = s.find('/');
numerator = stoi(s.substr(0, pos));
denominator = stoi(s.substr(pos+1, string::npos));
};
void exec(const frac&& d, char op){
int _lcm = lcm(denominator, d.denominator);
int num_d = d.numerator * (_lcm/d.denominator);
if(op == '+') numerator = (numerator * (_lcm/denominator)) + num_d
;
else numerator = (numerator * (_lcm/denominator)) - num_d;
denominator = _lcm;
if(numerator % denominator == 0){
numerator = numerator / denominator;
denominator = 1;
}
int _gcd = gcd(numerator, denominator);
if(_gcd != 1){
numerator /= _gcd;
denominator /= _gcd;
}
}
inline string to_str() { return to_string(numerator) + string(1, '/')
+ to_string(denominator); }
};
public:
string fractionAddition(string expression) {
vector<string> nums(1000, ""), ops;
int i = 0;
bool isnumerator=true, isdenominator=false;
for(auto c: expression){
if(isdenominator && (c == '+' || c == '-') ) {
ops.push_back(string(1,c));
isnumerator = true;
isdenominator = false;
i++;
} else if(isnumerator || isdenominator){
if(c == '/') {
isnumerator = false;
isdenominator = true;
}
nums[i] += c;
}
}
frac ans(nums[0]);
for(int i = 0; i < ops.size(); ++i){
ans.exec(frac(nums[i+1]), ops[i][0]);
}
return ans.to_str();
}
};