您的位置:首页 > 其它

Fraction to Recurring Decimal

2015-01-14 20:48 183 查看


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.

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)".

Java代码:



public class Solution {
public static String fractionToDecimal(int numerator, int denominator) {
String res = "";
long a = Math.abs((long) numerator);
long b = Math.abs((long) denominator);
if ((denominator < 0 && numerator > 0) || (denominator > 0 && numerator < 0)) {
res += "-";
}
long intPart= a / b;
res += intPart;
if (a % b == 0) {
return res;
}
res += ".";
long remainder = a % b;
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
int i = 1;
map.put(remainder, 1);
Queue<Long> queue = new LinkedList<Long>();
int begin = -1;
while (remainder != 0) {
i++;
long tmp = remainder * 10 / b;
remainder = remainder * 10 % b;
if (map.containsKey(remainder)) {
begin = map.get(remainder);
queue.offer(tmp);
break;
} else {
map.put(remainder, i);
queue.offer(tmp);
}
}
if (remainder == 0) {
while (!queue.isEmpty()) {
res += queue.poll();
}
} else {
int j = 1;
while (!queue.isEmpty()) {
long cur = queue.poll();
if (j != begin) {
res += cur;
} else {
res = res + "(" + cur;
}
j++;
}
res += ")";
}
return res;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: