题目:
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.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
解答:
看的discussion, 代码如下:
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
StringBuilder sb = new StringBuilder();
//判断正负性
sb.append((numerator > 0) ^ (denominator > 0) ? "-" : "");
long num = Math.abs((long)numerator);
long deno = Math.abs((long)denominator);
//加入整数部分
sb.append(num / deno);
num %= deno;
if (num == 0) {
return sb.toString();
}
//加入小数部分
sb.append(".");
//记录下已经出现过的numerator,当有重复的时候,即从前一个index开始到当前用“()”包含进去
Map<Long, Integer> map = new HashMap<Long, Integer>();
map.put(num, sb.length());
while (num != 0) {
num *= 10;
sb.append(num / deno);
num %= deno;
if (map.containsKey(num)) {
int index = map.get(num);
sb.insert(index, "(");
sb.append(")");
break;
} else {
map.put(num, sb.length());
}
}
return sb.toString();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。