Fraction to Recurring Decimal

**Fraction to Recurring Decimal**
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
class Solution {

    public String smartDivide(int x, int y){
        String result = "";
        long xx = x;
        long yy = y;
        long remain = 0;
        if(yy == 0) 
            return null;
        else if(xx == 0)
            return "0";
        else{
            result += xx / yy;
            remain = (xx - xx / yy * yy) > 0 ? (xx - xx / yy * yy) : -(xx - xx / yy * yy);
            yy = yy > 0? yy : -yy;
        }

        //记录每一步余数
        long divideRemain[] = new long[(int) (yy + 1)];
        divideRemain[0] = remain;
        if(remain != 0) 
            result += ".";
        boolean isDivided = false;
        for (int i = 1; i < divideRemain.length; i++) {
            if(divideRemain[i - 1] == 0){
                isDivided = true;
                break;
            }
            result += divideRemain[i - 1] * 10 / yy;
            divideRemain[i] = divideRemain[i - 1] * 10 - divideRemain[i - 1] * 10 / yy * yy;
        }

        //检查重复的余数
        if(isDivided == false){
            int i = 0, j = 0;
            breakout:
            for (i = 0; i < divideRemain.length - 1; i++) {
                for (j = i + 1; j < divideRemain.length; j++) {
                    if(divideRemain[i] == divideRemain[j]){
                        break breakout;
                    }
                }
            }

            String[] resultStrs = result.split("\\.");
            result = resultStrs[0] + "." + resultStrs[1].substring(0, i) + "(" + resultStrs[1].substring(i, j) + ")" ;
        }
        return result;
    }

}

你可能感兴趣的:(java)