Share my accepted solution


  • 1
    S
    public String fractionToDecimal(int numerator, int denominator) {
    	if (numerator == 0) return "0";
    	StringBuilder sb = new StringBuilder();
    	if (numerator < 0 ^ denominator < 0) sb.append('-');
    	long n = numerator < 0 ? -(long)numerator : (long)numerator;
    	long d = denominator < 0 ? -(long)denominator : (long)denominator;
    	sb.append(n/d);
    	if (n%d != 0){
    		sb.append('.');
    		if (decimal(n%d, d, sb.length(), sb, new ArrayList<>(), 0)) 
    			sb.append(')');
    	}
    	return sb.toString();
    }
    
    private boolean decimal(long n, long d, int start,StringBuilder sb, List<Long> rep, int count) {
    	if (n == 0) return false;
    	if (rep.contains(n)) {
    		sb.insert(rep.indexOf(n)+start, '(');
    		return true;
    	}
    	if (n < d){
    		rep.add(n);
    		return decimal(n*10, d, start, sb, rep, ++count);
    	} 
    	while (count-- > 1) sb.append('0');
    	sb.append(n/d);
    	return decimal(n%d, d, start, sb, rep, 0);
    }
    

Log in to reply
 

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