6

leetcode 166. 分数到小数

 3 years ago
source link: https://iamxcb.com/leetcode-166.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

leetcode 166. 分数到小数

发表于 2019-07-23

| 0

| 阅读次数:

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

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

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

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

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

示例代码(go)

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:] + ")"
}
Code 1: The app is disabled for violation of user agreement.
Powered By Valine
v1.3.9

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK