-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractiontoRecurringDecimal.cc
More file actions
67 lines (54 loc) · 1.52 KB
/
Copy pathFractiontoRecurringDecimal.cc
File metadata and controls
67 lines (54 loc) · 1.52 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
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
if (denominator == 0) return "";
string ans = "";
//如果结果为负数
if ((numerator < 0) ^ (denominator < 0)) {
ans += "-";
}
//下面要把两个数都转为正数,为避免溢出,int转为long
long num = numerator, den = denominator;
num = Math.abs(num);
den = Math.abs(den);
//结果的整数部分
long res = num / den;
ans += string.valueOf(res);
//如果能够整除,返回结果
long rem = (num % den) * 10;
if (rem == 0) return ans;
//结果的小数部分
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
ans += ".";
while (rem != 0) {
//如果前面已经出现过该余数,那么将会开始循环
if (map.containsKey(rem)) {
int beg = map.get(rem); //循环体开始的位置
string part1 = ans.substring(0, beg);
string part2 = ans.substring(beg, ans.length());
ans = part1 + "(" + part2 + ")";
return ans;
}
//继续往下除
map.put(rem, ans.length());
res = rem / den;
ans += string.valueOf(res);
rem = (rem % den) * 10;
}
return ans;
}
}
int main(int argc, char const *argv[])
{
/* code */
return 0;
}