• Time:O(n)
• Space:O(1)

C++

``````class Solution {
public:
istringstream iss(expression);
char _;
int a;
int b;
int A = 0;
int B = 1;

// init: A / B = 0 / 1
// A / B + a / b = (Ab + aB) / Bb
// so, each round set A = Ab + aB, B = Bb
while (iss >> a >> _ >> b) {
A = A * b + a * B;
B *= b;
const int g = abs(__gcd(A, B));
A /= g;
B /= g;
}

}
};
``````

JAVA

``````class Solution {
Scanner sc = new Scanner(expression).useDelimiter("/|(?=[+-])");
int A = 0;
int B = 1;

// init: A / B = 0 / 1
// A / B + a / b = (Ab + aB) / Bb
// so, each round set A = Ab + aB, B = Bb
while (sc.hasNext()) {
final int a = sc.nextInt();
final int b = sc.nextInt();
A = A * b + a * B;
B *= b;
final int g = gcd(A, B);
A /= g;
B /= g;
}

return A + "/" + B;
}

private int gcd(int a, int b) {
return a == 0 ? Math.abs(b) : gcd(b % a, a);
}
}
``````

Python

``````class Solution:
def fractionAddition(self, expression: str) -> str:
ints = list(map(int, re.findall('[+-]?[0-9]+', expression)))
A = 0
B = 1

for a, b in zip(ints[::2], ints[1::2]):
A = A * b + a * B
B *= b
g = math.gcd(A, B)
A //= g
B //= g

return str(A) + '/' + str(B)
``````