-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path166.cpp
More file actions
101 lines (79 loc) · 2.13 KB
/
166.cpp
File metadata and controls
101 lines (79 loc) · 2.13 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class Solution {
/*
* Converts integer to string.
*/
string intToString(long num)
{
string result = "";
while(num)
{
result += (char)((num % 10) + '0');
num /= 10;
}
reverse(result.begin(), result.end());
return result;
}
/*
* Make both numbers positive.
* Returns the positive or negative sign.
* Depends on the result.
*/
string processTheNumbers(long& n, long& d)
{
long prod;
prod = n * d;
n = abs(n);
d = abs(d);
if(prod < 0l)
return "-";
else
return "";
}
/*
* Checks for repetition of fractional part using memory (stores the value itself)
*/
string fractionPart(long n, long d)
{
vector<long> memory;
string result = "";
while(n)
{
int i = 0;
for(i = 0; i < memory.size(); i++)
if(memory[i] == n)
break;
if(i != memory.size())
{
result.insert(i, "(");
result += ')';
break;
}
result += (char)((n / d) + '0');
memory.push_back(n);
n = (n % d) * 10;
}
return result;
}
public:
string fractionToDecimal(int numerator, int denominator) {
if(numerator == 0 || denominator == 0)
return "0";
//Conversion is done to handle the INT_MIN case to make positive. (Out of Range)
long n = numerator, d = denominator;
string result = "";
result += processTheNumbers(n, d);
if((n % d) == 0)
return (result + intToString(n/d));
if(n > d)
{
result += intToString(n/d);
result += '.';
n = n % d;
}
else
result += "0.";
n = n * 10;
result += fractionPart(n, d);
return result;
}
};