leetcode 166. 分数到小数

题目描述

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。
如果小数部分为循环小数,则将循环的部分括在括号内。

示例 1:
输入: numerator = 1, denominator = 2
输出: “0.5”

示例 2:
输入: numerator = 2, denominator = 1
输出: “2”

示例 3:
输入: numerator = 2, denominator = 3
输出: “0.(6)”

题解

通过判断余数是否重复,找出循环小数的起始位置
分为三种情况:没有小数、小数不循环、小数循环

示例代码(go)

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
func fractionToDecimal(numerator int, denominator int) string {
isPositive := true
if numerator < 0 {
numerator = -numerator
isPositive = !isPositive
}
if denominator < 0 {
denominator = -denominator
isPositive = !isPositive
}
res := strconv.Itoa(numerator / denominator)
numerator = numerator % denominator
if numerator == 0 {
if !isPositive && res != "0" {
return "-" + res
}
return res
}
hash := make(map[int]int)
decimal := make([]string, 0)
i := 0
for numerator != 0 {
if _, ok := hash[numerator]; ok {
i = hash[numerator]
break
}
hash[numerator] = i
i++
numerator *= 10
str := strconv.Itoa(numerator / denominator)
decimal = append(decimal, str)
numerator = numerator % denominator
}
str := strings.Join(decimal, "")
if numerator == 0 {
if !isPositive {
return "-" + res + "." + str
}
return res + "." + str
}
if !isPositive {
return "-" + res + "." + str[:i] + "(" + str[i:] + ")"
}
return res + "." + str[:i] + "(" + str[i:] + ")"
}