Skip to content

Commit

Permalink
a166
Browse files Browse the repository at this point in the history
  • Loading branch information
chenzhengwei committed Feb 14, 2017
1 parent d35f009 commit 33f5e82
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ leetcode 题解

[144. Binary Tree Preorder Traversal](Solution/101-150/144.md)

[166. Fraction to Recurring Decimal](Solution/151-200/166.md)

[168. Excel Sheet Column Title](Solution/151-200/168.md)

[169. Majority Element](Solution/151-200/169.md)
Expand Down
46 changes: 46 additions & 0 deletions Solution/151-200/166.md
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();
}
}
```

0 comments on commit 33f5e82

Please sign in to comment.