#592
Medium Algorithms Fraction addition and subtraction
Math String Simulation
66.4% acceptance
Jan 13, 2026
891
696
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.
The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn fraction_addition(expression: String) -> String {
fn gcd(a: i64, b: i64) -> i64 { if b == 0 { a } else { gcd(b, a % b) } }
let expr = expression.as_bytes();
let n = expr.len();
let mut num = 0i64; let mut den = 1i64;
let mut i = 0usize;
while i < n {
let sign = if expr[i] == b'-' { i += 1; -1i64 } else { if expr[i] == b'+' { i += 1; } 1i64 };
let mut a = 0i64;
while i < n && expr[i].is_ascii_digit() { a = a * 10 + (expr[i] - b'0') as i64; i += 1; }
a *= sign;
i += 1; // skip '/'
let mut b = 0i64;
while i < n && expr[i].is_ascii_digit() { b = b * 10 + (expr[i] - b'0') as i64; i += 1; }
num = num * b + a * den;
den = den * b;
let g = gcd(num.abs(), den.abs());
num /= g; den /= g;
}
format!("{}/{}", num, den)
}
}