# Grokking #223

a guest
Jun 16th, 2022
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution {
2.     public String fractionToDecimal(int numerator, int denominator) {
3.         // Edge case: numerator is 0
4.         if (numerator == 0) {
5.             return "0";
6.         }
7.
8.         StringBuilder fraction = new StringBuilder();
9.         // If numerator and denominator have the different sign
10.         if (numerator < 0 ^ denominator < 0) {
11.             fraction.append("-");
12.         }
13.
14.         // integral part
15.         long dividend = Math.abs(Long.valueOf(numerator));
16.         long divisor = Math.abs(Long.valueOf(denominator));
17.         fraction.append(String.valueOf(dividend / divisor));
18.
19.         long remainder = dividend % divisor;
20.         if (remainder == 0) {
21.             return fraction.toString();
22.         }
23.
24.         // fractional part
25.         fraction.append(".");
26.         Map<Long, Integer> map = new HashMap<>();
27.         while (remainder != 0) {
28.             if (map.containsKey(remainder)) {
29.                 fraction.insert(map.get(remainder), "(");
30.                 fraction.append(")");
31.                 break;
32.             }
33.
34.             map.put(remainder, fraction.length());
35.             remainder *= 10;
36.             fraction.append(String.valueOf(remainder / divisor));
37.             remainder %= divisor;
38.         }
39.
40.         return fraction.toString();
41.     }
42. }