1 Star 0 Fork 0

Paulden/Algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
fraction_to_decimal.go 971 Bytes
一键复制 编辑 原始数据 按行查看 历史
Paulden 提交于 2022-09-20 16:25 . implement fraction to decimal
package algorithm
import "strconv"
// Problem Definition: https://leetcode.cn/problems/fraction-to-recurring-decimal/
func fractionToDecimal(numerator int, denominator int) string {
if numerator%denominator == 0 {
return strconv.Itoa(numerator / denominator)
}
var s []byte
if numerator*denominator < 0 {
s = append(s, '-')
}
numerator = abs(numerator)
denominator = abs(denominator)
integerPart := numerator / denominator
s = append(s, strconv.Itoa(integerPart)...)
s = append(s, '.')
indexMap := make(map[int]int, 0)
remainder := numerator % denominator
for remainder != 0 && indexMap[remainder] == 0 {
indexMap[remainder] = len(s)
remainder *= 10
s = append(s, '0'+byte(remainder/denominator))
remainder %= denominator
}
if remainder > 0 {
idx := indexMap[remainder]
s = append(s[:idx], append([]byte{'('}, s[idx:]...)...)
s = append(s, ')')
}
return string(s)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guuzaa/algorithm.git
git@gitee.com:guuzaa/algorithm.git
guuzaa
algorithm
Algorithm
main

搜索帮助