Skip to content

Commit 22d7e88

Browse files
author
applewjg
committed
FractionToRecurringDecimal
Change-Id: I47107ffba8924a2540c4fb5a4371ddbe5b8b1c06
1 parent 6f46427 commit 22d7e88

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

FractionToRecurringDecimal.h

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 15, 2014
4+
Problem: Fraction to Recurring Decimal
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/fraction-to-recurring-decimal/
7+
Notes:
8+
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
9+
10+
If the fractional part is repeating, enclose the repeating part in parentheses.
11+
12+
For example,
13+
14+
Given numerator = 1, denominator = 2, return "0.5".
15+
Given numerator = 2, denominator = 1, return "2".
16+
Given numerator = 2, denominator = 3, return "0.(6)".
17+
18+
Solution: ...
19+
*/
20+
class Solution {
21+
public:
22+
string fractionToDecimal(int numerator, int denominator) {
23+
if (numerator == 0) return string("0");
24+
bool flag = (numerator < 0)^(denominator < 0);
25+
long long Numerator = abs((long long)numerator);
26+
long long Denominator = abs((long long)denominator);
27+
string res;
28+
if (flag == true) res.push_back('-');
29+
ostringstream out;
30+
out << (Numerator / Denominator);
31+
res.insert(res.size(),out.str());
32+
Numerator = Numerator % Denominator;
33+
if (Numerator == 0) return res;
34+
res.push_back('.');
35+
unordered_map<int, int> map;
36+
for (int i = res.size(); Numerator != 0; ++i) {
37+
if (map.find(Numerator) != map.end()) break;
38+
map[Numerator] = i;
39+
Numerator *= 10;
40+
res.push_back((Numerator / Denominator) + '0');
41+
Numerator %= Denominator;
42+
}
43+
if (Numerator == 0) return res;
44+
res.insert(map[Numerator],"(");
45+
res.push_back(')');
46+
return res;
47+
}
48+
};

0 commit comments

Comments
 (0)