Skip to content

Commit e592860

Browse files
committed
Fraction to Recurring Decimal/ Excel Sheet Column Number
1 parent 309a3bd commit e592860

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''
2+
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
3+
4+
If the fractional part is repeating, enclose the repeating part in parentheses.
5+
6+
For example,
7+
8+
Given numerator = 1, denominator = 2, return "0.5".
9+
Given numerator = 2, denominator = 1, return "2".
10+
Given numerator = 2, denominator = 3, return "0.(6)".
11+
Hint:
12+
13+
No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
14+
Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
15+
Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
16+
'''
17+
18+
class Solution(object):
19+
def fractionToDecimal(self, numerator, denominator):
20+
"""
21+
:type numerator: int
22+
:type denominator: int
23+
:rtype: str
24+
"""
25+
sign = '-' if numerator * denominator < 0 else ''
26+
quotient, remainder = divmod(abs(numerator), abs(denominator))
27+
result_list = [sign, str(quotient), '.']
28+
remainders = []
29+
while remainder not in remainders:
30+
remainders.append(remainder)
31+
quotient, remainder = divmod(remainder * 10, abs(denominator))
32+
result_list.append(str(quotient))
33+
34+
idx = remainders.index(remainder)
35+
result_list.insert(idx + 3, '(')
36+
result_list.append(')')
37+
result = ''.join(result_list).replace('(0)', '').rstrip('.')
38+
return result
39+
40+
41+
if __name__ == "__main__":
42+
assert Solution().fractionToDecimal(1, 2) == '0.5'
43+
assert Solution().fractionToDecimal(2, 1) == '2'
44+
assert Solution().fractionToDecimal(2, 3) == '0.(6)'

171 Excel Sheet Column Number.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Related to question Excel Sheet Column Title
3+
4+
Given a column title as appear in an Excel sheet, return its corresponding column number.
5+
6+
For example:
7+
8+
A -> 1
9+
B -> 2
10+
C -> 3
11+
...
12+
Z -> 26
13+
AA -> 27
14+
AB -> 28
15+
'''
16+
17+
class Solution(object):
18+
def titleToNumber(self, s):
19+
"""
20+
:type s: str
21+
:rtype: int
22+
"""
23+
base = ord('A') - 1
24+
n = len(s)
25+
result = 0
26+
for i in range(n):
27+
result += (ord(s[n - 1 - i]) - base) * pow(26, i)
28+
return result
29+
30+
31+
if __name__ == "__main__":
32+
assert Solution().titleToNumber('A') == 1
33+
assert Solution().titleToNumber('AB') == 28

0 commit comments

Comments
 (0)