|
| 1 | +""" |
| 2 | +_________________________166. Fraction to Recurring Decimal_________________________ |
| 3 | +Difficulty: Medium Likes: 979 Dislikes: 2035 Solution: Available |
| 4 | +Total Accepted: 136.4K Total Submission: 621.9K Acceptance Rate: 21.9% |
| 5 | +Tags: Hash Table, Math |
| 6 | +
|
| 7 | +
|
| 8 | +Given two integers representing the numerator and denominator |
| 9 | +of a fraction, return the fraction in string format. |
| 10 | +If the fractional part is repeating, enclose the repeating part in parentheses. |
| 11 | +If multiple answers are possible, return any of them. |
| 12 | +It is guaranteed that the length of the answer |
| 13 | +string is less than 104 for all the given inputs. |
| 14 | + |
| 15 | + |
| 16 | +
|
| 17 | +
|
| 18 | +Example 1: Input: numerator = 1, denominator = 2 |
| 19 | + Output: "0.5" |
| 20 | + |
| 21 | +Example 2: Input: numerator = 2, denominator = 1 |
| 22 | + Output: "2" |
| 23 | + |
| 24 | +Example 3: Input: numerator = 2, denominator = 3 |
| 25 | + Output: "0.(6)" |
| 26 | + |
| 27 | +Example 4: Input: numerator = 4, denominator = 333 |
| 28 | + Output: "0.(012)" |
| 29 | + |
| 30 | +Example 5: Input: numerator = 1, denominator = 5 |
| 31 | + Output: "0.2" |
| 32 | + -231 <= numerator, denominator <= 231 - 1 denominator != 0 |
| 33 | +""" |
| 34 | + |
| 35 | + |
| 36 | +import functools, itertools, operator, bisect, array, collections |
| 37 | +from typing import * |
| 38 | + |
| 39 | +class Solution: |
| 40 | + def fractionToDecimal(self, N: int, D: int) -> str: |
| 41 | + if N==0: return '0' |
| 42 | + if D==1: return str(N) |
| 43 | + if N%D==0: return str(int(N//D)) |
| 44 | + |
| 45 | + d = {} |
| 46 | + if (N<0 and D<0) or (N>0 and D>0): |
| 47 | + res = '' |
| 48 | + else: |
| 49 | + res = '-' |
| 50 | + N = abs(N) |
| 51 | + D = abs(D) |
| 52 | + |
| 53 | + div, N = divmod(N, D) |
| 54 | + |
| 55 | + if div==0: |
| 56 | + res+='0.' |
| 57 | + else: |
| 58 | + res+=str(div)+'.' |
| 59 | + |
| 60 | + N*=10 |
| 61 | + idx = len(res) |
| 62 | + while N: |
| 63 | + div, t = divmod(N, D) |
| 64 | + if N in d: |
| 65 | + return res[:d[N]]+'('+res[d[N]:]+')' |
| 66 | + |
| 67 | + if div==0: |
| 68 | + res+='0' |
| 69 | + else: |
| 70 | + res+=str(div) |
| 71 | + |
| 72 | + d[N] = idx |
| 73 | + idx+=1 |
| 74 | + N = t*10 |
| 75 | + |
| 76 | + return res |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + s = Solution() |
| 81 | + print(s.fractionToDecimal(-50, 8)) |
| 82 | + |
| 83 | + |
| 84 | +""" |
| 85 | +""" |
0 commit comments