The title

Simulate long division

public String fractionToDecimal(int numerator, int denominator) { if (numerator == 0) { return "0"; } StringBuilder ans = new StringBuilder(); / / judgment sign if ((numerator < 0 && denominator > 0) | | (numerator > 0 && denominator < 0)) {ans. Append (" - "); } // convert to long to calculate long fenzi = math.abs (long.valueof (numerator)); long fenmu = Math.abs(Long.valueOf(denominator)); Long zhengShuShang = fenzi/fenmu; long yuShu = fenzi % fenmu; ans.append(zhengShuShang); If (yuShu == 0) {// Return ans.tostring (); } else {// Have decimal Map<Long, Integer> recordMap = new HashMap<>(); List<Long> shangRecord = new ArrayList<>(); int index = 0; while (yuShu ! = 0) { long temp = yuShu * 10; if (recordMap.containsKey(yuShu)){ int start = recordMap.get(yuShu); Anns.append ("."); // If the remainder is overquotient, it will be repeated. for (int i = 0; i < shangRecord.size(); i ++) { if (i == start) { ans.append("("); } ans.append(shangRecord.get(i)); } ans.append(")"); break; } shangRecord.add(temp / fenmu); recordMap.put(yuShu, index); yuShu = temp % fenmu; index ++; } if (yuShu == 0) { ans.append("."); For (int I = 0; i < shangRecord.size(); i ++) { ans.append(shangRecord.get(i)); } } } return ans.toString(); }Copy the code

The basic idea

  1. Using long division, which means if you were given two numbers and asked to do it by hand, how would you do it, that’s the core

  1. If a remainder is repeated, then the corresponding quotient is repeated, so it is necessary to record all occurrences of the remainder, and the order and value of their respective quotient

  2. The whole and fractional parts are counted separately, as are the cases with and without repeating decimals

  3. Math.abs(-2147483648) = -2147483648; math. abs(-2147483648) = -2147483648