1
+ /*
2
+
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