码迷,mamicode.com
首页 > 其他好文 > 详细

166. Fraction to Recurring Decimal

时间:2018-10-15 23:19:36      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:code   contains   思路   tostring   end   nbsp   string   integer   else   

一、题目

  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();                                                
    }

 

166. Fraction to Recurring Decimal

标签:code   contains   思路   tostring   end   nbsp   string   integer   else   

原文地址:https://www.cnblogs.com/skillking/p/9794940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!