leetcode 166: Fraction to Recurring Decimal
来源:互联网 发布:开源crm java 源码 编辑:程序博客网 时间:2024/05/29 07:23
There are some small tricks to solve the problem:
1. change the two numbers to long long.
2. sign problem when numerator/denominator==0.
3. use a unordered map to save different numerators and the indexes of the string before which I should insert a character '('.
class Solution {public: string fractionToDecimal(int numerator, int denominator) { string res; stringstream ss; long long _numerator=numerator; long long _denominator=denominator; bool sign=(_numerator<0)^(_denominator<0);//save the sign _numerator=_numerator<0?-_numerator:_numerator;//make it positive _denominator=_denominator<0?-_denominator:_denominator;//make it positive string str; ss<<_numerator/_denominator; ss>>str; ss.clear(); res+=str; _numerator%=_denominator; if(_numerator) res+='.'; unordered_map<long long,int> mp; string stemp; while(_numerator) { _numerator*=10; if(mp.find(_numerator)!=mp.end())//the duplicate exists { int idx=mp[_numerator]; res+=stemp.substr(0,idx); res+='('; res+=stemp.substr(idx); res+=')'; stemp.clear(); break; } mp.insert(make_pair(_numerator,stemp.size())); if(_numerator<_denominator) { stemp+='0'; continue; } stemp+=(_numerator/_denominator+'0'); _numerator%=_denominator; } res+=stemp; if(res!="0"&&sign) res="-"+res; return res; }};
0 0
- 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 166 Fraction to Recurring Decimal
- [leetcode] Fraction to Recurring Decimal
- LeetCode Fraction to Recurring Decimal
- Solarized Colorscheme for IntelliJ IDEA
- 让bootstrap的carousel支持滑动滚屏
- python异常处理和断言
- seek the name,seek the same
- Android-GridView (Simpleadapter)
- leetcode 166: Fraction to Recurring Decimal
- JavaScript 中的闭包(closure)是什么鬼?
- android textview 字体不同颜色
- 网络地址转换
- 确定字符互异(Java)
- 当前插入的线段能完整覆盖存在的几条线段 树状数组 HDU 5372 Segment Game
- Quartz2D-二维绘图引擎 、自定义UI控件
- TCP和UDP通信之间比较
- RPG黑暗之光(2)人物选择场景搭建、人物选择UI、人物选择控制