166. Fraction to Recurring Decimal

一、题目

  1、审题

  

  2、分析

    给出一个整数分子,一个整数分母。求商。若商为无限循环有理数,用括号包裹循环的小数。

 

二、解答

  1、思路:

    ①、先确定商的符号;可以采用 ^ 运算符;

    ②、计算商的整数部分;

    ③、计算商的小数部分;同时用一个 Map 记录当前小数数值以及插入的下标,用于判断是否是循环有理小数,并根据下标的位置插入括号。

    public String fractionToDecimal(int numerator, int denominator) {
     
        if(numerator == 0)
            return "0";
        
        StringBuilder res = new StringBuilder();
        
        // "+" or "-", ^ :  1 ^ 0 = 1, 1^1 = 0^0 = 0
        res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);    // 防止  -2147483648 溢出

        // Integer part
        res.append(num / den);
        num %= den;
        if(num == 0)
            return res.toString();
        
        // fractional part
        res.append(".");
        HashMap<Long, Integer> map = new HashMap<>();
        map.put(num, res.length());
        while(num != 0) {
            num *= 10;    // *
            res.append(num / den);
            num %= den;
            // 判断是否为无限循环小数
            if(map.containsKey(num)) {
                int index = map.get(num);
                res.insert(index, "(");
                res.append(")");
                break;
            }
            else {
                map.put(num, res.length());
            }
        }
        return res.toString();                                                
    }

 

posted @ 2018-10-15 21:45  skillking2  阅读(171)  评论(0编辑  收藏  举报