这个是我比较原始的解法。在这里有个trick就是把int扩展为long。要考虑负数情况,以及负数最小值的情况。

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        
        long lnumerator = numerator;
        long ldenominator = denominator;
        
        if (lnumerator == 0) {
            return "0";
        }
        
        boolean isPositive = true;
        
        if ((lnumerator >0 && ldenominator<0) || (lnumerator <0 && ldenominator>0)) {
            isPositive = false;
        }
        
        
        if (lnumerator < 0) {
            lnumerator = -lnumerator;
        }
        
        if (ldenominator < 0) {
            ldenominator = -ldenominator;
        }
        
        String left = "";
        if (lnumerator >= ldenominator && lnumerator % ldenominator == 0) {
            left = String.valueOf(lnumerator / ldenominator);
            if (!isPositive) {
                left = "-" + left;
            }
            return left;
        }
        
        if (denominator != 0) {
            
            long zhengshu = lnumerator / ldenominator;
            lnumerator = lnumerator % ldenominator;
            
            List<Long> yushus = new ArrayList<Long>();
            while (true) {
                long shang = lnumerator / ldenominator;
                long yushu = lnumerator % ldenominator;
                left = left + String.valueOf(shang);
                lnumerator = yushu * 10;
                if (shang == 0) {
                    yushus.add(yushu);
                    continue;
                } else if (yushu == 0) {
                    left = String.valueOf(zhengshu) + "." + left.substring(1);
                    if (!isPositive) {
                        left = "-" + left;
                    }
                    return left;
                } else {
                    for (int i = 0; i < yushus.size(); i++) {
                        if (yushus.get(i) == yushu) {
                            left =  String.valueOf(zhengshu) + "." + left.substring(1, i+1) + "(" + left.substring(i+1)  + ")";
                            if (!isPositive) {
                                left = "-" + left;
                            }
                            return left;
                        }
                    }
                }
                yushus.add(yushu);
            }
        }
        return left;
    }
}

chenatu
106 声望12 粉丝