LeetCode(166) Fraction to Recurring Decimal
来源:互联网 发布:淘宝买流量要验证码 编辑:程序博客网 时间:2024/06/10 21:13
题目
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)”.
分析
由上描述,本题要求得整数相除的结果,对循环小数用括号扩之;
首先,对于除数和被除数的特殊情况需分类处理;
然后,得到整数部分;
再次,分析小数部分,若有循环小数得到正确下标增加括号;
注意:整数的溢出问题;
先将int类型保存至long long类型;
AC代码
class Solution {public: string fractionToDecimal(int numerator, int denominator) { string str = ""; //除数为0,为异常情况 if (denominator == 0) return str; //被除数为0,结果为0 if (numerator == 0) return "0"; //异或,numerator<0和denominator<0仅有一个为真 if (numerator < 0 ^ denominator < 0) str += '-'; //转化为正数,INT_MIN转化为正数会溢出,故用long long;long long int n=abs(INT_MIN)得到的n仍然是负的,所以写成下面的形式 long long r = numerator; r = abs(r); long long d = denominator; d = abs(d); //得到整数部分并保存 str += to_string(r / d); r = r % d; //可以整除,直接返回 if (r == 0) return str; //添加小数点 str += "."; //下面处理小数部分,用哈希表 unordered_map<int, int> map; while (r){ //检查余数r是否在哈希表中,是的话则开始循环了 if (map.find(r) != map.end()){ str.insert(map[r], 1, '('); str += ')'; break; } map[r] = str.size(); //这个余数对应于result的哪个位置 //正常运算 r *= 10; str += to_string(r / d); r = r % d; } return str; } //整数到字符串的转换函数 string intToStr(long long num) { string str = ""; if (num < 10) { char c = num + '0'; return str + c; } else { while (num) { int d = num % 10; char c = d + '0'; str += c; num /= 10; }//while reverse(str.begin(), str.end()); return str; }//else }};
GitHub测试程序源码
0 0
- 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 NO.166 Fraction to Recurring Decimal
- Leetcode 166 Fraction to Recurring Decimal
- [Leetcode 166, Medium] 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
- LeetCode 166 Fraction to Recurring Decimal
- Leetcode学习之Fraction to Recurring Decimal(166)
- [leetcode-166]Fraction to Recurring Decimal(java)
- (动态规划)ural 1073 Square Country
- 接收短信的广播
- android(34)(有序广播、无序广播、中断特定号码广播、监听SD卡状态、横竖屏切换)
- shutdownNow关不掉线程
- Fraction to Recurring Decimal
- LeetCode(166) Fraction to Recurring Decimal
- Pow(x, n)
- Elasticsearch 2.1 安装
- PHP基础--页面传值,输入验证
- Java 理论与实践: 正确使用 Volatile 变量
- 为什么企业偏爱开源
- 欢迎使用CSDN-markdown编辑器
- ubuntu Mp3 to WAV pydub install
- hive中的分区表