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;
}
}
相关文章推荐
- [leetcode]Fraction to Recurring Decimal
- leetcode---Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal 哈希表
- [leetcode]Fraction to Recurring Decimal
- [leetcode] 166. Fraction to Recurring Decimal
- Leetcode Fraction to Recurring Decimal
- LeetCode 166 Fraction to Recurring Decimal
- 【Leetcode 166】 Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 103:Fraction to Recurring Decimal
- leetcode 166. Fraction to Recurring Decimal
- Fraction to Recurring Decimal 分数转为小数
- Fraction to Recurring Decimal
- LeetCode -- Fraction to Recurring Decimal
- LeetCode - Fraction to Recurring Decimal
- #leetcode#Fraction to Recurring Decimal
- Compare Version Numbers,Fraction to Recurring Decimal
- [leetcode] Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal