166. Fraction to Recurring Decimal - python3

3140 ワード

166. Fraction to Recurring Decimal
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
My Answer 1: Wrong Answer (22/38 test cases passed.)
class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        # 나누어 떨어지면 소수점 버리고 리턴
        if numerator % denominator == 0:
            return str(numerator//denominator) 
        
        # 순환소수?면 반복되는 부분 확인
        number = str(numerator/denominator).split(".")[1]
        repeating = ""
        result = str(numerator//denominator) + "."
        for i in range(len(number)):
            if number[i] in number[i+1:]:
                repeating += number[i]
            else:
                result += number[i]
            if repeating and number.count(repeating) != 1 and number.count(repeating) * len(repeating) == len(number[i-len(repeating)+1:]):
                result += "(" + repeating + ")"
                
                return result
            
        return str(numerator/denominator)

  • 分割する場合は、小数点を捨ててreturn=>//を使用します.

  • 循環小数点以下の重複部分をチェック
    numberに小数点以下の桁数を保存し、繰り返し検索
  • でも….0.011111111111111112のように重複する部分があるわけではありません...
    どうしたらいいか分からない.
    Solution 1: Runtime: 32 ms - 64.24%/Memory Usage: 14.3 MB - 70.41%
    class Solution:
        def fractionToDecimal(self, numerator: int, denominator: int) -> str:
            if numerator == 0: return '0'
            
            result = []
            if numerator < 0 and denominator > 0 or numerator >= 0 and denominator < 0:
                result.append('-')
            
            numerator, denominator = abs(numerator), abs(denominator)
            
            result.append(str(numerator // denominator))
            
            remainder = numerator % denominator
            
            if remainder == 0: return ''.join(result)
            result.append('.')
            
            d = {}
            while remainder != 0:
                if remainder in d:
                    result.insert(d[remainder], '(')
                    result.append(')')
                    return ''.join(result)
                
                d[remainder] = len(result)
                
                remainder *= 10
                result += str(remainder // denominator)
                remainder = remainder % denominator
            
            return ''.join(result)

  • 結果値が負の場合はresultに-(負)を加え、分子、分母を終端値に置き換えます.

  • 結果に小数点以下の1部のみを入れ、残りの部分に残りを保存します.

  • 残りが0なら別れるので、すぐ結果に戻ります.
    または小数点(.)入れる

  • dicksherner dを使用してインデックス値を保存し、残りの値が0になる前にループします.

  • 残りの値がdにある場合、=>重複する部分である場合
    「≪結果|Results|emdw≫」で、繰り返しの開始索引値にかっこを付けて戻ります.

  • 残りを分割した後、シェアをresultに更新し、残りをresultに更新します.