当前位置:网站首页>Fraction to recursing decimal

Fraction to recursing decimal

2022-06-23 06:02:00 ruochen

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)".
  1. First judge the symbol , Use Math.signum(). If it's a positive number , return 1; negative , return -1; yes 0, return 0.
  2. Considering spillover , Auxiliary variables are defined as long. This is because if : So in numerator * 10 after , It overflowed .
  3. To take the absolute value , because -2 % 3 = -2, -2 % -3 = -2
  4. analysis 57, The remainder is respectively 5 1 3 2 6 4 5, To 5 There is a cycle at . Because the remainder must be [0,7) Within the scope of , If you can't get rid of , It must be an infinite circular decimal . The position of the loop , Is the position where a remainder first appears , To the current position where the remainder appears ( The remainder is one of the remainder , The first to appear 2 Time of ).
    public String fractionToDecimal(int numerator, int denominator) {
        String sign = "";
        if (Math.signum(numerator) * Math.signum(denominator) < 0) {
            sign = "-";
        }
        long n = Math.abs(numerator);
        long d = Math.abs(denominator);
        String intPart = Math.abs(n / d) + "";
        //  If you divide it , Direct return 
        if (n % d == 0) {
            return sign + intPart;
        }
        //  Calculate the decimal part 
        n %= d;
        n *= 10;
        StringBuilder sb = new StringBuilder();
        Map<Long, Integer> mod = new HashMap<Long, Integer>();
        for (int i = 0; n != 0; i++) {
            long q = n / d;
            Integer start = mod.get(n / 10);
            if (start != null) {
                sb.insert(start, "(");
                sb.append(")");
                break;
            }
            sb.append(Math.abs(q));
            mod.put(n / 10, i);
            n %= d;
            n *= 10;
        }
        String fractionalPart = sb.toString();
        return sign + intPart + "." + fractionalPart;
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201151252028683.html