166. Fraction to Recurring Decimal Leetcode Python

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.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

we need to used a hash table to store current numerator to deal with recurring scenarios. 

code is as follow:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值