Skip to content

Commit c45acab

Browse files
committed
fraction_to_recurring_decimal
1 parent 91db34d commit c45acab

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
143143
#### [162. Find Peak Element](https://github.com/hitzzc/go-leetcode/tree/master/find_peak_element)
144144
#### [164. Maximum Gap](https://github.com/hitzzc/go-leetcode/tree/master/maximum_gap)
145145
#### [165. compare version numbers](https://github.com/hitzzc/go-leetcode/tree/master/compare_version_numbers)
146+
#### [166. Fraction to Recurring Decimal](https://github.com/hitzzc/go-leetcode/tree/master/fraction_to_recurring_decimal)
146147

147148

148149

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package fraction_to_recurring_decimal
2+
3+
import (
4+
"strconv"
5+
)
6+
7+
func fractionToDecimal(numerator int, denominator int) string {
8+
if numerator == 0 {
9+
return "0"
10+
}
11+
m := []byte("0123456789")
12+
var ret string
13+
var neg bool
14+
if numerator < 0 {
15+
numerator *= -1
16+
neg = !neg
17+
}
18+
if denominator < 0 {
19+
denominator *= -1
20+
neg = !neg
21+
}
22+
if neg {
23+
ret = "-"
24+
}
25+
ret += strconv.Itoa(numerator / denominator)
26+
remainder := numerator % denominator
27+
if remainder == 0 {
28+
return ret
29+
}
30+
ret += "."
31+
floatBytes := []byte{}
32+
indexMap := map[int]int{}
33+
for remainder != 0 {
34+
if idx, ok := indexMap[remainder]; ok {
35+
return ret + string(floatBytes[:idx]) + "(" + string(floatBytes[idx:]) + ")"
36+
}
37+
indexMap[remainder] = len(floatBytes)
38+
remainder *= 10
39+
v := m[remainder/denominator]
40+
remainder %= denominator
41+
floatBytes = append(floatBytes, v)
42+
}
43+
return ret + string(floatBytes)
44+
}

0 commit comments

Comments
 (0)