aboutsummaryrefslogtreecommitdiff
path: root/fraction_to_recurring_decimal.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-09-23 22:57:45 -0600
committerJack Sangdahl <[email protected]>2025-09-23 22:57:45 -0600
commitff0500a7e8c426a0a6f46076761869fc88098d87 (patch)
tree744b345c338c8cffb2acd7ed4e587e25531484f1 /fraction_to_recurring_decimal.py
parent5e2e4726603b20bc5a876e308807c3bf97f37776 (diff)
downloadleetcode-ff0500a7e8c426a0a6f46076761869fc88098d87.tar.gz
leetcode-ff0500a7e8c426a0a6f46076761869fc88098d87.zip
166. fraction to recurring decimal
Diffstat (limited to 'fraction_to_recurring_decimal.py')
-rw-r--r--fraction_to_recurring_decimal.py36
1 files changed, 36 insertions, 0 deletions
diff --git a/fraction_to_recurring_decimal.py b/fraction_to_recurring_decimal.py
new file mode 100644
index 0000000..e77819c
--- /dev/null
+++ b/fraction_to_recurring_decimal.py
@@ -0,0 +1,36 @@
+# 166. Fraction to Recurring Decimal
+
+"""
+given two integers representing the 'numerator' and 'denominator' of a
+fraction, reeturn 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 10^4 for all the digits given inputs.
+"""
+
+
+class Solution(object):
+ def fractionToDecimal(self, numerator, denominator):
+ """
+ :type numerator: int
+ :type denominator: int
+ :rtype: str
+ """
+ n, rem = divmod(abs(numerator), abs(denominator))
+ sign = "-" if numerator * denominator < 0 else ""
+ ans, stack = [sign + str(n), "."], []
+ while rem not in stack:
+ stack.append(rem)
+ n, rem = divmod(rem * 10, abs(denominator))
+ ans.append(str(n))
+ idx = stack.index(rem)
+ ans.insert(idx + 2, "(")
+ ans.append(")")
+ return "".join(ans).replace("(0)", "").rstrip(".")
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.fractionToDecimal(1, 2))
+ print(obj.fractionToDecimal(2, 1))
+ print(obj.fractionToDecimal(4, 333))