166. Fraction to Recurring Decimal
https://www.cnblogs.com/grandyang/p/4238577.html
用一个哈希表判断余数是否重复,重复了就有无限循环小数,就可以停止加括号了
class Solution { public: string fractionToDecimal(int numerator, int denominator) { int flag1 = numerator > 0 ? 1 : -1; int flag2 = denominator > 0 ? 1 : -1; long num1 = abs((long)numerator); long num2 = abs((long)denominator); long num = num1 / num2; long rem = num1 % num2; unordered_map<int,int> m; string res = to_string(num); if(flag1 * flag2 == -1 && (num != 0 || rem != 0)) res = "-" + res; if(rem == 0) return res; res += "."; int index = res.size(); while(rem){ if(m.find(rem) != m.end()){ res.insert(m[rem],"("); res += ")"; return res; } m[rem] = index; num = rem*10 / num2; rem = rem*10 % num2; res += to_string(num); ++index; } return res; } };
自己又写了一遍
class Solution { public: string fractionToDecimal(int numerator, int denominator) { if(denominator == 0) return ""; bool flag; if((numerator >= 0 && denominator > 0) || (numerator <= 0 && denominator < 0)) flag = true; else flag = false; long num1 = abs((long)numerator); long num2 = abs((long)denominator); long num = num1/num2; long rem = num1%num2; string res; res += to_string(num); if(!flag) res = "-" + res; if(rem == 0) return res; res += "."; unordered_map<long,int> m; int index = res.size(); while(rem != 0){ if(m.find(rem) != m.end()){ res.insert(m[rem],"("); res += ")"; return res; } m[rem] = index; long tmp = rem*10/num2; rem = rem*10%num2; res += to_string(tmp); index++; } return res; } };