103:Fraction to Recurring Decimal

来源:互联网 发布:叶子老师沪江辞职知乎 编辑:程序博客网 时间:2024/05/01 13:29

题目: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)”.

解析:这题目难点在于如何找到无限循环的那一段。通过手工推演除法计算过程,我们会发现当一个余数第二次重复出现时,小数点后就开始循环了,代码如下:

// 通过手工计算除法,我们会发现当一个余数第二次重复出现时// 小数点后就开始无限循环了class Solution {public:        string fractionToDecimal(int numerator, int denominator) {                string res = "";                if (numerator == 0) return "0";                if (denominator == 0) return res;                // int 表示的范围是 [-2147483648, 2147483647]                // 因此 int 的最小值变为正数时会越界                // 所以把其赋给长整形 long                long n = numerator;                long d = denominator;                if ((n < 0 && d > 0) || (n > 0 && d < 0))                        res = "-";                if (n < 0) n = -n;                if (d < 0) d = -d;                res += to_string(n / d);                n = n % d;                if (n == 0) return res;                res += '.';                int pos = res.size();                // map 用来记录被除数为 n 时相应的商在                // 返回字符串 res 中的位置,方便以后添加'('                unordered_map<long, int> record;                // 模拟除法的过程                while (n != 0) {                        if (record.find(n) != record.end()) {                                res.insert(res.begin() + record[n], '(');                                res += ')';                                return res;                        }                        record[n] = pos; // 表示 n * 10 / d 结果所插入的位置                        res += char(n * 10 / d + '0');                        ++pos;                        n = (n * 10) % d;                }                return res;        }};
0 0
原创粉丝点击