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