leetcode 166 分数到小数
我是傻逼。若结果中出现循环,每一次获得的余数也会是循环,所以用一个哈希表来存放所有的余数,当余数出现重复时,代表结果中也出现了重复,从而将左括号插入该余数的下标处,从而完成任务,贴代码
1 class Solution { 2 public: 3 string fractionToDecimal(int numerator, int denominator) 4 { 5 string res; 6 long n = 0; 7 long d = 0; 8 long flag = 1; 9 if(numerator == INT_MIN && denominator == -1) 10 { 11 n = long(INT_MAX)+1; 12 d = 1; 13 flag = 1; 14 } 15 else 16 { 17 n = numerator>=0 ? numerator:-1*long(numerator); 18 d = denominator>0 ? denominator:-1*long(denominator); 19 flag = (numerator>=0 && denominator>0) || (numerator<0 && denominator<0) ? 1:-1; 20 } 21 if(n == 0) 22 return "0"; 23 if(flag == -1) 24 res+='-'; 25 res.append(to_string(n/d)); 26 n = n%d; 27 if(n == 0) 28 return res; 29 res+='.'; 30 int index = res.size()-1; 31 unordered_map<int,int> record; 32 while(n && record.count(n) == 0) 33 { 34 record[n] = ++index; 35 n *= 10; 36 res += to_string(n/d); 37 n = n%d; 38 } 39 if(record.count(n) == 1) 40 { 41 res.insert(record[n],"("); 42 res.push_back(')'); 43 } 44 return res; 45 } 46 };

浙公网安备 33010602011771号