zoukankan      html  css  js  c++  java
  • 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)".

    解决思路

    关键点:HashMap中存的是除数和除数的位置。

    程序

    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            long n = Long.valueOf(numerator);
            long d = Long.valueOf(denominator);
            StringBuilder res = new StringBuilder();
            
            // sign
            if ((n > 0 && d < 0) || (n < 0 && d > 0)) {
                res.append("-");
            }
            
            // abs
            n = Math.abs(n);
            d = Math.abs(d);
            
            long r = n / d;
            res.append(r);
            n = (n % d) * 10;
            if (n != 0) {
                res.append("."); // whether has decimal 
            } else {
                return res.toString();
            }
            
            HashMap<Long, Integer> map = new HashMap<>(); // 存的是除数和此时的位置
            while (n != 0) {
                long dit = n / d;
                if (map.containsKey(n)) {
                    // cycle
                    String s1 = res.toString().substring(0, map.get(n));
                    String s2 = res.toString().substring(map.get(n));
                    return s1 + "(" + s2 + ")";
                }
                map.put(n, res.length());
                res.append(dit);
                n = (n % d) * 10;
            }
            
            return res.toString();
        }
    }
    
  • 相关阅读:
    l1-013
    将博客搬至CSDN
    Educational Codeforces Round 25
    大组合数取余模板【Lucas定理】
    Exams(二分求左界+贪心)
    Cutting (暴力 + 滚动哈希判字符串匹配)
    Cubes(DFS+剪枝)
    Codeforces Round #409 (Div. 2)
    【复习挖坑】dp + 图
    n & n-1 和 n & -n
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4717326.html
Copyright © 2011-2022 走看看