-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path166.cpp
More file actions
38 lines (36 loc) · 849 Bytes
/
166.cpp
File metadata and controls
38 lines (36 loc) · 849 Bytes
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
//
// 166.cpp
// leetcode
//
// Created by R Z on 2018/7/23.
// Copyright © 2018年 R Z. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
string fractionToDecimal(int64_t n, int64_t d) {
if(n==0) return "0";
string res="";
if(n<0 ^ d<0) res+="-";
n=abs(n), d=abs(d);
if(n/d>0) res+=to_string(n/d);
else res+="0";
if(n%d==0) return res;
else res+=".";
unordered_map<int,int> map;
for(int64_t r=n%d; r; r%=d){
if(map.count(r)>0){
res.insert(map[r],1,'(');
res+=")";
break;
}
map[r]=res.size();
r*=10;
res+=to_string(r/d);
}
return res;
}
};