Skip to main content
Back to problems
#166
Medium Algorithms

Fraction to recurring decimal

Hash Table Math String
30.6% acceptance
Jan 12, 2026
2584
3859
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs. Note that if the fraction can be represented as a finite length string, you must return it.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn fraction_to_decimal(numerator: i32, denominator: i32) -> String {
    if numerator == 0 {
      return "0".to_string();
    }
    
    let mut result = String::new();
    let num = numerator as i64;
    let den = denominator as i64;
    
    if (num < 0) ^ (den < 0) {
      result.push('-');
    }
    
    let num = num.abs();
    let den = den.abs();
    
    result.push_str(&(num / den).to_string());
    
    let remainder = num % den;
    if remainder == 0 {
      return result;
    }
    
    result.push('.');
    let mut remainder_map = std::collections::HashMap::new();
    let mut remainder = remainder;
    
    while remainder != 0 {
      if let Some(&pos) = remainder_map.get(&remainder) {
        result.insert(pos, '(');
        result.push(')');
        break;
      }
      
      remainder_map.insert(remainder, result.len());
      remainder *= 10;
      result.push_str(&(remainder / den).to_string());
      remainder %= den;
    }
    
    result
  }
}