本文主要是介绍Golang | Leetcode Golang题解之第166题分数到小数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
func fractionToDecimal(numerator, denominator int) string {if numerator%denominator == 0 {return strconv.Itoa(numerator / denominator)}s := []byte{}if numerator < 0 != (denominator < 0) {s = append(s, '-')}// 整数部分numerator = abs(numerator)denominator = abs(denominator)integerPart := numerator / denominators = append(s, strconv.Itoa(integerPart)...)s = append(s, '.')// 小数部分indexMap := map[int]int{}remainder := numerator % denominatorfor remainder != 0 && indexMap[remainder] == 0 {indexMap[remainder] = len(s)remainder *= 10s = append(s, '0'+byte(remainder/denominator))remainder %= denominator}if remainder > 0 { // 有循环节insertIndex := indexMap[remainder]s = append(s[:insertIndex], append([]byte{'('}, s[insertIndex:]...)...)s = append(s, ')')}return string(s)
}func abs(x int) int {if x < 0 {return -x}return x
}
这篇关于Golang | Leetcode Golang题解之第166题分数到小数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!