Java for LeetCode 166 Fraction to Recurring Decimal

时间:2024-12-26 11:36:26

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)".
解题思路:

测试中会出现各种临界值,因此,需要先将 numerator 和 denominator转为long,然后计算出整数部分,对于小数部分,将numerator*10后处理,一方面将计算除后的值放到一个list中,另一方面将新的分子放到map里,由于新分子肯定小于denominator,所以肯定会出现0或者重复(因此分数要么有限,要么是无限循环小数)一旦新分母重复出现,意味着结果会出现循环值,将其按照规则写出来即可,JAVA实现如下:

    public String fractionToDecimal(int numerator, int denominator) {
StringBuilder sb = new StringBuilder();
if (numerator < 0 && denominator > 0)
sb.append("-");
else if (numerator > 0 && denominator < 0)
sb.append("-");
Long Lnumerator = (long) numerator;
if (Lnumerator < 0)
Lnumerator = -Lnumerator;
Long Ldenominator = (long) denominator;
if (Ldenominator < 0)
Ldenominator = -Ldenominator;
if (Lnumerator % Ldenominator == 0){
sb.append(Lnumerator / Ldenominator);
return sb.toString();
}
sb.append(Lnumerator / Ldenominator + ".");
System.out.println(Lnumerator);
Lnumerator %= Ldenominator;
System.out.println(Lnumerator);
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
map.put(Lnumerator, 0);
while (true) {
Lnumerator *= 10;
while (Lnumerator < Ldenominator) {
list.add(0);
map.put(Lnumerator, list.size());
Lnumerator *= 10;
}
list.add((int) (Lnumerator / Ldenominator));
Lnumerator %= Ldenominator;
if (Lnumerator == 0) {
for (int i = 0; i < list.size(); i++)
sb.append(list.get(i));
return sb.toString();
} else if (map.containsKey(Lnumerator)) {
for (int i = 0; i < map.get(Lnumerator); i++)
sb.append(list.get(i));
sb.append("(");
for (int i = map.get(Lnumerator); i < list.size(); i++)
sb.append(list.get(i));
sb.append(")");
return sb.toString();
}
map.put(Lnumerator, list.size());
}
}