[LeetCode] 166. Fraction to Recurring Decimal
来源:互联网 发布:分时量比曲线源码 编辑:程序博客网 时间:2024/06/08 09:46
思路:
参考https://discuss.leetcode.com/topic/6079/accepted-cpp-solution-with-explainations/24. 这题的最难点在于找循环体. 循环体是要找分子对于分母的余数何时重复, 如果当前余数在之前出现过了就说明从此时开始循环了, 所以要拿一个哈希记录所有出现过的余数的位置. 然后还有要注意的是所有数字类型都要用长整型, 这样可以避免overflow的情况.
string fractionToDecimal(long long numerator, long long denominator) { // 分母为0直接返回空字符串 if (! denominator) return ""; // 分子为0直接返回"0" if (! numerator) return "0"; string res = ""; // 确定是否有负号 if (numerator < 0 ^ denominator < 0) res += '-'; // 分子分母去符号 long long n = abs(numerator); long long d = abs(denominator); // 结果串添加整数部分 res += to_string(n / d); // 如果整除了就结束, 直接返回结果串 if (! (n % d)) return res; // 添加小数点 res += '.'; long long r = n % d; unordered_map<long long, int> m; while (r) { // 余数出现过了, 添加括号, 返回结果串 if (m.count(r)) { res.insert(m[r], 1, '('); res += ')'; return res; } m[r] = res.length(); // 继续取余, 并把结果添加到结果串中 r *= 10; res += to_string(r / d); r %= d; } return res;}
0 0
- 166. Fraction to Recurring Decimal Leetcode Python
- Leetcode-166.Fraction to Recurring Decimal
- [Leetcode]166. Fraction to Recurring Decimal @python
- [leetcode] 166. Fraction to Recurring Decimal
- leetcode 166. Fraction to Recurring Decimal
- [LeetCode]166. Fraction to Recurring Decimal
- LeetCode *** 166. Fraction to Recurring Decimal
- LeetCode 166. Fraction to Recurring Decimal
- [LeetCode]problem 166. Fraction to Recurring Decimal
- leetcode-java-166. Fraction to Recurring Decimal
- LeetCode 166. Fraction to Recurring Decimal
- [LeetCode] 166. Fraction to Recurring Decimal
- Leetcode-166. Fraction to Recurring Decimal
- leetcode 166. Fraction to Recurring Decimal
- Leetcode 166. Fraction to Recurring Decimal
- LeetCode 166. Fraction to Recurring Decimal
- Leetcode 166. Fraction to Recurring Decimal
- leetCode 166. Fraction to Recurring Decimal
- java不同数据类型在内存中的存储方式
- andorid 自定义View 命名空间 长话短说
- iOS 制作圆形图片
- 双向循环链表——STL迭代器
- iOS10适配问题
- [LeetCode] 166. Fraction to Recurring Decimal
- hdu 5256 序列变换 -LIS 严格转非严格
- 【Easy】206. Reverse Linked List
- 微信公众号测试号申请及访问
- 404错误解决新思路
- Rabbitmq 流控
- 写个脚本生成库链接
- ubuntu16.04(2) -中文输入问题
- POJ 1886简单模拟