[InterviewBit] Fraction

Fraction

  • Time :
  • Space :
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
string Solution::fractionToDecimal(int a, int b) {
bool sign = true;
long long A = a, B = b;
if(1ll * A * B < 0) sign = false;
A = abs(A), B = abs(B);
long long pos = A / B, id = 0;
A = A % B;
if(A == 0) return (sign ? "" : "-") + to_string(pos);
map<pair<int,int>, int> hash;
string prime = "";
while(A) {
A *= 10;
long long rem = A % B;
long long div = A / B;
if(hash.count({rem,div})) {
prime = prime.substr(0,hash[{rem,div}]) + "(" + prime.substr(hash[{rem,div}]) + ")";
A = 0;
} else {
hash[{rem,div}] = id++;
prime.push_back(div | 0b110000);
A = rem;
}
}
return (sign ? "" : "-") + to_string(pos) + "." + prime;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/24/PS/interviewbit/fraction/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.