Fraction to Recurring Decimal
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
- Given numerator = 1, denominator = 2, return "0.5".
- Given numerator = 2, denominator = 1, return "2".
- Given numerator = 2, denominator = 3, return "0.(6)".
两个问题:
1.如何找到循环小时部分,解决方法是Hash table,存储已经出现过的余数,当他再次出现说明开始循环了。这和Happy Number解法一样,Hash table判断是否有循环出现。
2.INT的最大值和最小值,比如INT_MIN=-2147483648,取绝对值后就超过了INT_MAX=2147483647了,解决方法是使用long long类型。
1 class Solution { 2 public: 3 string fractionToDecimal(int numerator, int denominator) { 4 string result; 5 long long num=numerator,den=denominator; 6 if(numerator==0) 7 { 8 return "0"; 9 } 10 if((numerator<0)^(denominator<0)) 11 { 12 result+='-'; 13 } 14 if(numerator<0) 15 { 16 num=-1*num; 17 } 18 if(denominator<0) 19 { 20 den=-1*den; 21 } 22 long long int_part=num/den; 23 result+=to_string(int_part); 24 if(num%den==0) 25 { 26 return result; 27 } 28 result+='.'; 29 long long left=num%den; 30 unordered_map<long long,int> showed; 31 while(left) 32 { 33 if(showed.find(left)!=showed.end()) 34 { 35 int position=showed[left]; 36 string part1=result.substr(0,position); 37 string part2=result.substr(position,result.length()); 38 result = part1+'('+part2+')'; 39 return result; 40 } 41 showed[left]=result.length(); 42 left*=10; 43 int dig=left/den; 44 result+=to_string((long long)dig); 45 left = left%den; 46 } 47 return result; 48 } 49 };