每天一题 Leetcode 166. Fraction to Recurring Decimal
利用哈希表找重复情况,注意corner case。
每天一题 Leetcode 166. Fraction to Recurring Decimal
1. 题目
https://leetcode.com/problems/fraction-to-recurring-decimal/
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
Example 1:Input: numerator = 1, denominator = 2Output: "0.5"Example 2:Input: numerator = 2, denominator = 1Output: "2"Example 3:Input: numerator = 2, denominator = 3Output: "0.(6)"Example 4:Input: numerator = 4, denominator = 333Output: "0.(012)"Example 5:Input: numerator = 1, denominator = 5Output: "0.2"
Constraints:
-231 <= numerator, denominator <= 231 - 1
denominator != 0
2. 解法
代码:
import(
"strconv"
"fmt"
)
func abs(n int) int {
if n > 0 {
return n
}
return -n
}
func fractionToDecimal(numerator int, denominator int) string {
var res string
if ((numerator > 0) && (denominator < 0)) || ((numerator < 0) && (denominator > 0)){
res += "-"
}
num := abs(numerator)
den := abs(denominator)
res += strconv.Itoa(num/den)
num %= den
if num == 0{
return res
}
res += "."
numMap := make(map[int]int)
numMap[num] = len(res)
for num != 0 {
num *= 10
res += strconv.Itoa(num/den)
num %= den
if index, ok := numMap[num];ok{
res = res[:index] + "(" + res[index:] + ")"
break
}else{
numMap[num] = len(res)
}
}
return res
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!