Skip to content

Commit 2f71a7b

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 18.2 MB (20.31%)
1 parent 3b788a7 commit 2f71a7b

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p>
2+
3+
<p>If the fractional part is repeating, enclose the repeating part in parentheses.</p>
4+
5+
<p>If multiple answers are possible, return <strong>any of them</strong>.</p>
6+
7+
<p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> numerator = 1, denominator = 2
14+
<strong>Output:</strong> &quot;0.5&quot;
15+
</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> numerator = 2, denominator = 1
21+
<strong>Output:</strong> &quot;2&quot;
22+
</pre>
23+
24+
<p><strong class="example">Example 3:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> numerator = 4, denominator = 333
28+
<strong>Output:</strong> &quot;0.(012)&quot;
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li>
36+
<li><code>denominator != 0</code></li>
37+
</ul>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
3+
if numerator == 0:
4+
return "0"
5+
6+
neg = (numerator < 0) != (denominator < 0)
7+
result = []
8+
if neg:
9+
result.append("-")
10+
11+
num, denom = abs(numerator), abs(denominator)
12+
result.append(str(num // denom))
13+
num %= denom
14+
15+
if num == 0:
16+
return "".join(result)
17+
result.append(".")
18+
19+
hash_map = {}
20+
while num:
21+
hash_map[num] = len(result)
22+
num *= 10
23+
result.append(str(num // denom))
24+
num %= denom
25+
if num in hash_map:
26+
result.insert(hash_map[num], "(")
27+
result.append(")")
28+
break
29+
30+
return "".join(result)

0 commit comments

Comments
 (0)