Question

Formatted question description: https://leetcode.ca/all/166.html

 166	Fraction to Recurring Decimal

 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.

 Example 1:

 Input: numerator = 1, denominator = 2
 Output: "0.5"

 Example 2:

 Input: numerator = 2, denominator = 1
 Output: "2"

 Example 3:

 Input: numerator = 2, denominator = 3
 Output: "0.(6)"

 @tog-top100

Algorithm

Int needs to be converted to long type before taking the absolute value.

To find the cycle is to get another number, see if this number appears before. In order to save search time, we use a hash table to store the number in each decimal position.

There is also a little trick, because you have to calculate each decimal position, the method adopted is to multiply the remainder by 10 each time, and then divide by the divisor, the quotient obtained is the next digit of the decimal. When the newly calculated number has appeared before in map, add a left parenthesis at the beginning of the loop and a right parenthesis at the end.

Code

Java

  • import java.util.HashMap;
    
    public class Fraction_to_Recurring_Decimal {
    
         // test: 5 / 6 = 0.833333 = 0.8(3)
    
        public static void main(String[] args) {
            Fraction_to_Recurring_Decimal out = new Fraction_to_Recurring_Decimal();
            Solution s = out.new Solution();
    
            System.out.println(s.fractionToDecimal(-1, -2147483648));
        }
    
        class Solution {
    
            public String fractionToDecimal(int numeratorOriginal, int denominatorOriginal) {
    
                // @note: sign
                long n1 = numeratorOriginal > 0 ? 1 : -1;
                long n2 = denominatorOriginal > 0 ? 1 : -1;
                String sign = n1 * n2 > 0 ? "" : "-";
    
                // @note: missed below, after getting sign, convert to all positives
                /*
    
                    @note: below will error if directly get abs
                            for int, abs(-2147483648) = -2147483648
    
                    numerator = Math.abs(numerator); // possible overflow
                    denominator = Math.abs(denominator); // possible overflow
    
                */
    
                long numerator = Math.abs((long)numeratorOriginal); // possible overflow
                long denominator = Math.abs((long)denominatorOriginal); // possible overflow
    
                if (denominator == 0) {
                    return "";
                } else if (numerator == 0) {
                    return "0";
                } else if (numerator % denominator == 0) {
                    return sign + String.valueOf(numerator / denominator);
                }
    
                StringBuilder result = new StringBuilder();
                result.append(sign);
    
                // hashmap to save if a repeated result, meaning recurring
                HashMap<Long, Integer> hm = new HashMap<>();
    
                // digit before .
                result.append(String.valueOf(numerator / denominator));
    
                result.append(".");
    
                // digit after .
                long end = 10 * (numerator % denominator);
                int i = 1;
    
                // test: 1 / 4 = 0.25
                while (end != 0) { // @note: stop condition
                    if (hm.containsKey(end)) {
                        // recurring
                        int pos = hm.get(end);
                        result.insert(result.indexOf(".") + pos, "(");
                        result.append(")");
    
                        return result.toString(); // break and return
                    }
    
                    hm.put(end, i);
                    result.append(end / denominator);
    
                    System.out.println(result.toString());
    
                    i++;
                    end = 10 * (end % denominator);
                }
    
                return result.toString();
            }
        }
    }
    
  • Todo
    
  • class Solution(object):
      def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
        ans = "-" if numerator * denominator < 0 else ""
        numerator = abs(numerator)
        denominator = abs(denominator)
        ans += str(numerator / denominator)
        if numerator % denominator:
          ans += "."
        numerator = (numerator % denominator) * 10
        if numerator == 0:
          return ans
        d = {}
        res = []
        while True:
          r = numerator % denominator
          v = numerator / denominator
          if numerator in d:
            idx = d[numerator]
            return ans + "".join(res[:idx]) + "(" + "".join(res[idx:]) + ")"
          res.append(str(v))
          if v == 0:
            d[numerator] = len(res) - 1
            numerator *= 10
            continue
          d[numerator] = len(res) - 1
          numerator = r * 10
          if r == 0:
            return ans + "".join(res)
        return ans + "".join(res)
    
    

All Problems

All Solutions