Skip to content

Latest commit

 

History

History

166

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

 

Example 1:

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

Example 2:

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

Example 3:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

 

Constraints:

  • -231 <= numerator, denominator <= 231 - 1
  • denominator != 0

Companies: ServiceNow, Goldman Sachs, Airbnb, MathWorks, Facebook, Microsoft, Amazon, Snapchat, IXL, Google

Related Topics:
Hash Table, Math, String

Solution 1.

The integer part is of length lg(N/D). The fractional part is at most of length D according to pigeon hole principle.

// OJ: https://leetcode.com/problems/fraction-to-recurring-decimal
// Author: github.com/lzl124631x
// Time: O(lg(N/D) + D)
// Space: O(lg(N/D) + D)
class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        string ans;
        long long n = numerator, d = denominator;
        if ((n < 0 && d > 0) || (n > 0 && d < 0)) ans += '-';
        n = abs(n);
        d = abs(d);
        ans += to_string(n / d);
        if (n % d) ans += '.';
        unordered_map<int, int> numToIndex;
        while ((n = n % d * 10) && numToIndex.count(n) == 0) {
            numToIndex[n] = ans.size();
            ans += '0' + n / d;
        }
        if (n) { // repeating part detected
            ans.insert(numToIndex[n], 1, '(');
            ans += ')';
        }
        return ans;
    }
};