[
math
hash table
string
]
BinarySearch 0407 Decimal Number
Problem statement
https://binarysearch.com/problems/Decimal-Number/
Solution
Equal to Leetcode 0166 Fraction to Recurring Decimal.
Complexity
Time and memory complexity is O(n)
, where n
is lengh of preperiod and period
Code
class Solution:
def solve(self, x, y):
n, rem = divmod(abs(x), abs(y))
sign = '-' if x*y < 0 else ''
x, y = abs(x), abs(y)
result = [sign + str(n), '.']
rems = {}
while rem > 0 and rem not in rems:
rems[rem] = len(result)
n, rem = divmod(rem*10, y)
result += [str(n)]
if rem in rems:
idx = rems[rem]
result.insert(idx, '(')
result += [')']
return ''.join(result).rstrip(".")