zoukankan      html  css  js  c++  java
  • 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();                                                
        }
  • 相关阅读:
    C 语言定义
    一次系统磁盘异常使用100%的处理
    supervisord 安装、配置体验
    uva 211(dfs)
    poj1651
    有一种感动叫ACM(记WJMZBMR在成都赛区开幕式上的讲话)
    nyoj-746
    Codeforces Round #308 (Div. 2)----C. Vanya and Scales
    long long 与 _int64
    石子归并问题(nyoj737)
  • 原文地址:https://www.cnblogs.com/skillking/p/9794940.html
Copyright © 2011-2022 走看看