LeetCode 166. Fraction to Recurring Decimal(模拟)
- 2020 年 2 月 14 日
- 笔记
题意:给出一个分数的分子和分母,给出这个分数的小数形式的字符串模式。循环的部分用( 括上。
题解:模拟除法,判断循环体。
class Solution { public: map<int,int> m; string fractionToDecimal(int numerator, int denominator) { long long int numerator_ = numerator; long long int denominator_ = denominator; int sign = 1; if(numerator_<0&&denominator_>0) { sign = 0; } else if(numerator_>0&&denominator_<0) { sign = 0; } if(numerator_<0) numerator_ *= -1; if(denominator_<0) denominator_ *= -1; string ans=""; if(numerator_ > denominator_) { long long int x = numerator_ / denominator_; numerator_ = numerator_ % denominator_; ans += to_string(x); } else { ans += '0'; } m[numerator_] = 1; if(numerator_!=0) ans+='.'; int tag=1; int pos=0; while(numerator_!=0) { numerator_ *= 10; long long int x = numerator_ / denominator_ ; ans += (x+'0'); numerator_ = numerator_ % denominator_; if(numerator_==0) break; if(m[numerator_]!=0) { pos = m[numerator_]; break; } else { m[numerator_]=++tag; } } string res=""; if(sign==0) res += '-'; int i; tag=-1; int tag2=0; for(i=0;i<ans.length();i++) { if(tag==pos) { res+='('; tag2=1; } res+=ans[i]; if(tag>=1) { tag++; } if(ans[i]=='.') { tag=1; } } if(tag2==1) res+=')'; return res; } };