Fraction to Recurring Decimal
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 | Input: numerator = 1, denominator = 2 |
Example 2:
1 | Input: numerator = 2, denominator = 1 |
Example 3:
1 | Input: numerator = 2, denominator = 3 |
思路:一开始采用了字符串判断循环的算法,发现可能出现的情况太多了,没有办法求解。后来看到了一个非常巧妙的算法,我们每次都作除,然后取整数部分,然后余数*10,继续下去。直到我们发现之前出现过的被除数出现了就说明这中间的就是循环体,然后取出来即可。这道题还需要考虑正负的不同情况,以及int型的边界溢出情况。代码如下:
1 | class Solution { |