Fraction To Recurring Decimal Problem


Description

LeetCode Problem 166.

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 10^4 for all the given inputs.

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

Constraints:

  • -2^31 <=numerator, denominator <= 2^31 - 1
  • denominator != 0


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
string fractionToDecimal(int numerator, int denominator) {
	if (!numerator) {
		return "0";
	}

	string result;
	long long remainder = numerator;
	unordered_map<long long, int> pattern;

	// Determine sign so that we don't have to care about it later.
	if ((remainder < 0 && denominator > 0) ||
		(remainder > 0 && denominator < 0)) {
		result += "-";
	}

	while (remainder) {
		result += to_string(llabs(remainder / denominator));
		remainder = remainder % denominator;

		// Each time we got a new remainder, check if it matches a repeat pattern. 
		if (pattern.find(remainder) != pattern.end()) {
			result.insert(pattern[remainder], "(");
			result.append(")");
			break;
		}

		// If we are not done by dividing once, we need a ".".
		if (remainder && result.find('.') == result.npos) {
			result += ".";
		}

		// Save the remainder and its correspounding position in the result.
		pattern[remainder] = result.length();

		remainder *= 10;
	}

	return result;
}




Related Posts

Repeated DNA Sequences Problem

LeetCode 187. The DNA sequence is composed of a series...

Majority Element Problem

LeetCode 169. Given an array nums of size n, return...

Fraction To Recurring Decimal Problem

LeetCode 166. Given two integers representing the numerator and denominator...

Max Points On A Line Problem

LeetCode 149. Given an array of points where points[i] =...

Lru Cache Problem

LeetCode 146. Design a data structure that follows the constraints...

Longest Consecutive Sequence Problem

LeetCode 128. Given an unsorted array of integers nums, return...