zoukankan      html  css  js  c++  java
  • [LeetCode] 167. 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.

    Example 1:

    Input: numerator = 1, denominator = 2
    Output: "0.5"
    

    Example 2:

    Input: numerator = 2, denominator = 1
    Output: "2"

    Example 3:

    Input: numerator = 2, denominator = 3
    Output: "0.(6)"

    给2个整数分别作分子和分母,返回分数的字符串形式。

    Java:

    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            if (numerator == 0) {
                return "0";
            }
            StringBuilder res = new StringBuilder();
            // "+" or "-"
            res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
            long num = Math.abs((long)numerator);
            long den = Math.abs((long)denominator);
            
            // integral part
            res.append(num / den);
            num %= den;
            if (num == 0) {
                return res.toString();
            }
            
            // fractional part
            res.append(".");
            HashMap<Long, Integer> map = new HashMap<Long, Integer>();
            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();
        }
    }
    

    Python:

    class Solution(object):
        def fractionToDecimal(self, numerator, denominator):
            """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
            result = ""
            if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
                result = "-"
    
            dvd, dvs = abs(numerator), abs(denominator)
            result += str(dvd / dvs)
            dvd %= dvs
    
            if dvd > 0:
                result += "."
    
            lookup = {}
            while dvd and dvd not in lookup:
                lookup[dvd] = len(result)
                dvd *= 10
                result += str(dvd / dvs)
                dvd %= dvs
    
            if dvd in lookup:
                result = result[:lookup[dvd]] + "(" + result[lookup[dvd]:] + ")"
    
            return result
    

    C++:

    // upgraded parameter types
    string fractionToDecimal(int64_t n, int64_t d) {
        // zero numerator
        if (n == 0) return "0";
    
        string res;
        // determine the sign
        if (n < 0 ^ d < 0) res += '-';
    
        // remove sign of operands
        n = abs(n), d = abs(d);
    
        // append integral part
        res += to_string(n / d);
    
        // in case no fractional part
        if (n % d == 0) return res;
    
        res += '.';
    
        unordered_map<int, int> map;
    
        // simulate the division process
        for (int64_t r = n % d; r; r %= d) {
    
            // meet a known remainder
            // so we reach the end of the repeating part
            if (map.count(r) > 0) {
                res.insert(map[r], 1, '(');
                res += ')';
                break;
            }
    
            // the remainder is first seen
            // remember the current position for it
            map[r] = res.size();
    
            r *= 10;
    
            // append the quotient digit
            res += to_string(r / d);
        }
    
        return res;
    }
    

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    array and ram
    char as int
    pointer of 2d array and address
    Install SAP HANA EXPRESS on Google Cloud Platform
    Ubuntu remount hard drive
    Compile OpenSSL with Visual Studio 2019
    Install Jupyter notebook and tensorflow on Ubuntu 18.04
    Build OpenCV text(OCR) module on windows with Visual Studio 2019
    Reinstall VirtualBox 6.0 on Ubuntu 18.04
    Pitfall in std::vector<cv::Mat>
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9770473.html
Copyright © 2011-2022 走看看