Monday, August 24, 2015

Leetcode 166. Fraction to Recurring Decimal

https://leetcode.com/problems/fraction-to-recurring-decimal/

The hard part is how to get repeated fraction number. The answer is that when the dividend appears twice, there will be such situation.

Solution:
# T:O(lgn) S:O(1)
class Solution:
    # @param {integer} numerator
    # @param {integer} denominator
    # @return {string}
    def fractionToDecimal(self, numerator, denominator):
        dvd, dvs = abs(numerator), abs(denominator)
        integer, decimal, dict = "", '', {}
        
        if dvd > dvs:
            integer = str(dvd / dvs)
            dvd %= dvs
        else:
            integer = "0"
        
        if dvd > 0:
            integer += "."
        
        idx = 0
        while dvd:
            if dvd in dict:
                decimal = decimal[:dict[dvd]] + "(" + decimal[dict[dvd]:] + ")"
                break
            
            dict[dvd] = idx
            idx += 1
            
            dvd *= 10
            decimal += str(dvd / dvs)
            dvd %= dvs
        
        if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0): 
            return "-" + integer + decimal
        else:
            return integer + decimal
Run Time: 44 ms

No comments:

Post a Comment