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
原创粉丝点击