-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathfraction.cpp
More file actions
55 lines (44 loc) · 1.21 KB
/
Copy pathfraction.cpp
File metadata and controls
55 lines (44 loc) · 1.21 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
string solve_fraction_to_decimal(int numerator, int denominator) {
if(numerator == 0) {
return "0";
}
long long num = abs((long) numerator);
long long den = abs((long) denominator);
bool is_negative = (numerator < 0) ^ (denominator < 0);
string result;
if(is_negative) {
result += "-";
}
long long whole_part = num / den;
result += to_string(whole_part);
long long rem = num % den;
if(rem == 0) {
return result;
}
result += ".";
unordered_map<long long, long long> rem_positions;
long long repeat_index;
bool is_repeating = false;
while(rem > 0 && !is_repeating) {
if(rem_positions.count(rem)) {
repeat_index = rem_positions[rem];
is_repeating = true;
break;
}
else {
rem_positions[rem] = result.size();
}
rem *= 10;
long long quotient = rem / den;
result += to_string(quotient);
rem = rem % den;
}
if(is_repeating) {
result.insert(repeat_index, "(");
result += ")";
}
return result;
}
string Solution::fractionToDecimal(int A, int B) {
return solve_fraction_to_decimal(A, B);
}