My java solution


  • 0
    S

    public String fractionToDecimal(int numerator, int denominator) {
    if (denominator == 0){return "";}
    long n = numerator, d = denominator;
    n = n < 0 ? -n : n;
    d = d < 0 ? -d : d;

    HashMap<Long, Integer> map = new HashMap<Long, Integer>();
    int index = 0;
    String s = Long.toString(n/d);
    n = n%d;
    if (n != 0){s+=".";}
    index += s.length();
    while(n > 0){
        if (map.get(n) == null){
        	map.put(n, index);    
        } else {
            // Recurring decimal pattern found
            s = s.substring(0, map.get(n)) + "(" + s.substring(map.get(n), index) + ")";
            break;
        }
        n *=10;
        s += Long.toString(n/d);
        index++;
        n %= d;            
    }
    
    if ((numerator < 0 && denominator>0) || (numerator >0 && denominator<0)) { s = "-" + s;};
    return s;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.