-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionToRecurringDecimal.cpp
More file actions
executable file
·70 lines (60 loc) · 1.72 KB
/
FractionToRecurringDecimal.cpp
File metadata and controls
executable file
·70 lines (60 loc) · 1.72 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
//
// FractionToRecurringDecimal.cpp
// leetcode
//
// Created by witwolf on 5/12/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string result = integerPart(numerator, denominator);
if(numerator != 0){
result.append(".").append(fractionalPart(numerator, denominator));
}
return result;
}
private:
inline string fractionalPart(int numerator,int denominator){
string result;
map<int,size_t> pos;
while(numerator){
numerator *= 10;
if(pos.find(numerator) != pos.end()){
result.insert(pos[numerator], 1,'(');
result.push_back(')');
break;
}
pos[numerator] = result.size();
result.push_back(numerator / denominator + '0');
numerator %= denominator;
}
return result;
}
inline string integerPart(int &numerator,int &denominator){
int integer_part = numerator / denominator;
numerator = abs( numerator % denominator );
denominator = abs(denominator);
return itoa(integer_part);
}
inline string itoa(int i){
stringstream ss;
ss << i;
return ss.str();
}
};
int main(int argc,char **argv){
Solution s;
while(true){
int numerator,demoninator;
cin >> numerator >> demoninator ;
cout << numerator << '/' << demoninator << '=' << s.fractionToDecimal(numerator, demoninator) << endl;
}
}