美文网首页Leetcode
Leetcode.166.Fraction to Recurri

Leetcode.166.Fraction to Recurri

作者: Jimmy木 | 来源:发表于2019-11-13 14:14 被阅读0次

题目

给定两个数, 一个除数, 一个被除数, 输出结果, 如果是循环小数, 用括号把循环位括起来.

Input: -50, 8
Output: -6.25
Input: -1, -2147483648
Output: 0.0000000004656612873077392578125
Input: 1, 7
Output: 0.(142857)
Input: 53, 6
Output: 8.8(3)

思路

计算小数, 分为整数部分和小数部分.
先确定符号.
计算出整数部分.
计算可以除尽的小数部分.
计算除不尽的循环部分.
int在考虑符号时很容易越界.

 string fractionToDecimal(int numerator, int denominator) {
     string res;
     // 整数部分
     bool isSameSimple = true;
     if ((numerator < 0 && denominator > 0) ||
         (numerator > 0 && denominator < 0)) {
         isSameSimple = false;
         res += "-";
     }
     int64_t a = abs((int64_t)numerator / (int64_t)denominator);
     res += to_string(a);
     if (isSameSimple) {
         numerator -= a * denominator;
     }else{
         numerator += a * denominator;
     }
     // 小数部分
     string leftStr;
     string leftLoop;
     unordered_map<int64_t, int> map;
     while(numerator != 0) {
         int64_t newNum = (int64_t)numerator * 10;
         numerator = newNum % denominator;
         if (map.count(newNum) > 0) {
            leftLoop = leftStr.substr(map[newNum]);
            leftStr = leftStr.substr(0, map[newNum]);
             break;
         }
         map[newNum] = (int)leftStr.size();
         leftStr += to_string(abs(newNum / denominator));
     }

     if (leftStr.size() > 0 || leftLoop.size() > 0) {
         res += "." + leftStr;
         if(leftLoop.size() > 0) {
             res += "(" + leftLoop + ")" ;
         }
     }

     return res;
 }

总结

int越界问题比较麻烦, 符号问题也比较繁琐, 最好先处理好符号.
思路要清晰, 不能总数尝试, 要彻底梳理好思路再下手.

相关文章

网友评论

    本文标题:Leetcode.166.Fraction to Recurri

    本文链接:https://www.haomeiwen.com/subject/jhvhictx.html