首页 > 代码库 > [LeetCode] Fraction to Recurring Decimal
[LeetCode] 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)".
这题实现起来还是比较麻烦的,主要还要考虑负数的输入情况,特别是-2147483648这样的整数型的边界值。最简单的方法就是先把所有的输入全部转换为长整型的正数。
另外,由于要记录小数里循环的部分,所以还需要用到一个Map去记录小数点的每位和对应的余数值。如果碰到的同样的余数值,那么说明遇到了开始循环的部分了。
public String fractionToDecimal(int numerator, int denominator) { long longNumerator = Math.abs((long) numerator); long longDenominator = Math.abs((long) denominator); StringBuilder sb = new StringBuilder(); if ((long) numerator * denominator < 0) sb.append("-"); sb.append(longNumerator / longDenominator); long remainder = longNumerator % longDenominator; if (remainder == 0) return sb.toString(); sb.append("."); StringBuilder fracSb = new StringBuilder(); Map<Long, Integer> map = new HashMap<Long, Integer>(); int index = 0; while (remainder != 0) { remainder *= 10; long nextRemainder = remainder % longDenominator; // If repeated part occurs. if (map.containsKey(remainder)) { fracSb.insert(map.get(remainder), "("); fracSb.append(")"); break; } map.put(remainder, index++); fracSb.append(remainder / longDenominator); remainder = nextRemainder; } sb.append(fracSb); return sb.toString(); }
[LeetCode] Fraction to Recurring Decimal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。