首先这题要考虑,若被除数为0,显然返回0,如果两个数一正一负,显然是不好处理的,因此要先把除法结果的正负号记下来。然后对被除数和除数都做取绝对值的处理。
为了处理循环小数,用一个哈希表记录下每一步下来的余数,如果这一步的余数和之前的重复说明陷入循环,就需要找到之前余数出现的位置前,对他进行加括号处理,具体代码如下:
class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
## denominator can be 0 but do not need to consider here
if numerator == 0:
return '0'
neg = False
if numerator > 0 and denominator < 0 or numerator < 0 and denominator > 0:
neg = True
if numerator % denominator == 0:
return str(numerator / denominator)
numerator = abs(numerator)
denominator = abs(denominator)
table = {}
res = ""
res += str(numerator / denominator)
res += '.'
numerator %= denominator
i = len(res)
while numerator:
if numerator not in table:
table[numerator] = i
else:
i = table[numerator]
res = res[:i] + '(' + res[i:] + ')'
if neg:
return '-' + res
else:
return res
numerator = numerator * 10
res += str(numerator/denominator)
numerator %= denominator
i+=1
if neg:
return '-' + res
return res