首页 > 其他 > 详细

将分数转化为小数

时间:2019-09-23 23:33:47      阅读:152      评论:0      收藏:0      [点我收藏+]

leet code 166. Fraction to Recurring Decimal

题目:https://leetcode.com/problems/fraction-to-recurring-decimal/

题解:https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/51160/C%2B%2B-unordered_map

题目的内容为:给定两个数n和d,n作为分子,d作为分母,给出分数对应的小数字符串。如果小数循环,使用()将循环部分括起来。

例子:

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

边界条件题。需要注意的边界包括:符号、小数点、小数循环。这种题记得就行,没有需要算法的地方。

符号可以使用异或处理。即(n > 0 ^ d > 0),同号为0,异号为1。

小数点可以根据余数判断。第一次相除后的余数为0,则没有小数。

小数循环则需要判断余数是否之前已经出现过,如果已经出现,从上次出现到这次之前的部分就是循环部分。

总的代码如下:

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (!numerator) return "0";
        string res;
        // first, decide the sign
        if (numerator > 0 ^ denominator > 0) res += "-";
        // then, decide the integral part
        // attention, negative number can have a large range than positive number
        long n = labs(numerator), d = labs(denominator) , r = n % d;
        res += to_string(n / d);
        // decide the point
        if (!r) return res;
        res += ".";
        // decide the fractional part
        // use a map to deal with repeating part
        unordered_map<long, int> rs;
        while(r){
            // if the rem shows again, then repeat from last time to this time
            if (rs.find(r) != rs.end()){
                res.insert(rs[r], "(");
                res += ")";
                break;
            }
            // save where the r appears
            rs[r] = res.size();
            r *= 10;
            // get next quotient
            res += to_string(r / d);
            r %= d;
        }
        return res;
    }
};

 

将分数转化为小数

原文:https://www.cnblogs.com/vimery/p/11575584.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!