166. Fraction to Recurring Decimal - python3

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)
  1. 나눠 떨어지면 소수점 버리고 리턴 => // 사용

  2. 순환소수면 반복되는 부분 확인
    number 에 소수점 자리를 저장하고 반복문 돌려서 repeating 을 찾음

근데... 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)
  1. 결과값이 음수면 result 에 -(마이너스) 를 넣어주고 numerator, denominator 둘다 절댓값으로 바꿈

  2. result 에 소수점 제외 몫만 넣어주고 remainder 에 나머지를 저장해준다.

  3. 나머지가 0 이면 나눠 떨어지니까 바로 result 리턴
    아니면 소수점(.) 을 넣어준다

  4. 딕셔너리 d 를 이용해서 인덱스 값 저장, remainder 가 0 이 될 때까지 반복문을 돌림

  5. remainder 값이 d 에 있으면 => 반복되는 부분이면
    result 속 반복의 시작 인덱스 값에 괄호를 넣어주고 리턴

  6. remainder 를 나눈 후 몫은 result 에 나머지는 remainder 에 업데이트

좋은 웹페이지 즐겨찾기