码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 166 Fraction to Recurring Decimal

时间:2015-07-04 15:33:35      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:


class Solution:
    # @param {integer} numerator
    # @param {integer} denominator
    # @return {string}
    def fractionToDecimal(self, numerator, denominator):
        negativeFlag = numerator * denominator < 0
        numerator = abs(numerator); denominator = abs(denominator)
        numsList = [];count = 0; dictLoop = {}; loopstr = None
        while True:
            numsList.append(str(numerator / denominator))
            numerator = 10 * (numerator%denominator)
            if numerator == 0:  break
            count += 1
            loc= dictLoop.get(numerator)
            if loc:
                loopstr = ''.join(numsList[loc:count])
                break
            dictLoop[numerator] = count
        result = numsList[0]
        if len(numsList) > 1: result += '.'
        if loopstr:
            result += ''.join(numsList[1:len(numsList)-len(loopstr)])  + '(' + loopstr + ')'
        else:
            result += ''.join(numsList[1:])
        if negativeFlag: result = '-' + result
        return result



版权声明:本文为博主原创文章,未经博主允许不得转载。

Leetcode 166 Fraction to Recurring Decimal

标签:

原文地址:http://blog.csdn.net/andrew9tech/article/details/46755207

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!