166. Fraction to Recurring Decimal
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了166. 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.
Example 1:
Input: numerator = 1, denominator = 2 Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1 Output: "2"
Example 3:
Input: numerator = 2, denominator = 3 Output: "0.(6)"
public class Solution { public String fractionToDecimal(int numerator, int denominator) { if (numerator == 0) { return "0"; } StringBuilder res = new StringBuilder(); // "+" or "-" res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : ""); long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); // integral part res.append(num / den); num %= den; if (num == 0) { return res.toString(); } // fractional part res.append("."); HashMap<Long, Integer> map = new HashMap<Long, Integer>(); map.put(num, res.length()); while (num != 0) { num *= 10; res.append(num / den); num %= den; System.out.println(num); if (map.containsKey(num)) { int index = map.get(num); res.insert(index, "("); res.append(")"); break; } else { map.put(num, res.length()); } } return res.toString(); } }
class Solution { public String fractionToDecimal(int numerator, int denominator) { StringBuilder result = new StringBuilder(); String sign = (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-"; long num = Math.abs((long) numerator); long den = Math.abs((long) denominator); result.append(sign); result.append(num / den); long rem = num % den; if (rem == 0) return result.toString(); result.append("."); Map<Long, Integer> map = new HashMap(); //store numerator as repetition of same numerator will cause recurring while(rem != 0){ if(!map.containsKey(rem)){ map.put(rem, result.length()); //for a given numerator its (num*10)/den starts from this idx }else { int idx = map.get(rem); return result.substring(0, idx)+"("+result.substring(idx)+")"; } rem*= 10; result.append(rem/den); rem = rem%den; } return result.toString(); }
以上是关于166. Fraction to Recurring Decimal的主要内容,如果未能解决你的问题,请参考以下文章
166. Fraction to Recurring Decimal
166. Fraction to Recurring Decimal
166. Fraction to Recurring Decimal
166. Fraction to Recurring Decimal