Python store numerators


  • 0
        def fractionToDecimal(self, numerator, denominator):
            if denominator == 0: return "NaN"
            if numerator % denominator == 0: return str(numerator / denominator)
            nums, first, res = {}, True, ""
            if (numerator * denominator) < 0: res += "-"
            numerator, denominator = abs(numerator), abs(denominator)
            while numerator != 0:
                calc = numerator // denominator
                numerator -= denominator * calc
                res += str(calc)
                # add decimal point for first calculation
                if first: first, res = False, res + "."
                if numerator in nums: 
                    res = res[:nums[numerator]] + "(" +  res[nums[numerator]:] + ")"
                    break
                nums[numerator] = len(res)
                numerator *= 10
            return res 
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.