166. Fraction to Recurring Decimal
Difficulty: Medium
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
1 2
|
Input: numerator = 1, denominator = 2 Output: "0.5"
|
Example 2:
1 2
|
Input: numerator = 2, denominator = 1 Output: "2"
|
Example 3:
1 2
|
Input: numerator = 2, denominator = 3 Output: "0.(6)"
|
解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class : def fractionToDecimal(self, num: int, denom: int) -> str: tag = -1 if num * denom < 0 else 1 num, denom = abs(num), abs(denom) re_num = '' dic = {} while 1: if not re_num: value = num // denom num = num % denom re_num += str(value) if num == 0: return re_num if tag == 1 else '-' + re_num else: re_num += '.' dic[str(num)] = len(re_num) else: num *= 10 value = num // denom num = num % denom re_num += str(value) if num == 0: return re_num if tag == 1 else '-' + re_num else: if str(num) in dic: re_num = re_num[:dic[str(num)]] + '(' + re_num[dic[str(num)]:] + ')' return re_num if tag == 1 else '-' + re_num else: dic[str(num)] = len(re_num)
|
近期评论