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; } };
