-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
chenzhengwei
committed
Feb 14, 2017
1 parent
d35f009
commit 33f5e82
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
#166. Fraction to Recurring Decimal | ||
[题目链接](https://leetcode.com/problems/fraction-to-recurring-decimal/) | ||
```java | ||
public class Solution { | ||
public String fractionToDecimal(int numerator, int denominator) { | ||
if (numerator == 0) | ||
return "0"; | ||
StringBuilder sb = new StringBuilder(); | ||
if ((numerator > 0) ^ (denominator > 0)) { | ||
sb.append('-'); | ||
} | ||
// 考虑边界值,因为int型负数比正数多一,所以转换为long | ||
long num = Math.abs((long)numerator); | ||
long den = Math.abs((long)denominator); | ||
if (num < den) { | ||
sb.append(0); | ||
} else { | ||
sb.append(num/den); | ||
} | ||
long rest = num % den; | ||
if (rest == 0) { | ||
return sb.toString(); | ||
} | ||
sb.append('.'); | ||
Map<Long, Integer> numMap = new HashMap<>(); | ||
int repeatFlag = 0; | ||
StringBuilder smallSb = new StringBuilder(); | ||
numMap.put(rest, repeatFlag++); | ||
// 求小数部分,把重复余数的位置记录下来,当遇到重复余数是,说明有无限循环部分 | ||
while (rest != 0) { | ||
rest *= 10; | ||
smallSb.append(rest / den); | ||
rest = rest % den; | ||
if (numMap.containsKey(rest)) { | ||
int repeatStart = numMap.get(rest); | ||
String snum = smallSb.toString(); | ||
sb.append(snum.substring(0, repeatStart)); | ||
sb.append('(').append(snum.substring(repeatStart)).append(')'); | ||
return sb.toString(); | ||
} | ||
numMap.put(rest, repeatFlag++); | ||
} | ||
return sb.append(smallSb).toString(); | ||
} | ||
} | ||
``` |