1. void populateAfterDecimal(long num,long den,string &res){
  2. // key : remainder
  3. // value : position in res where the remainder occured for the first time
  4. unordered_map<long, long> m;
  5.  
  6. string ans = "";
  7. while(num){
  8. // if num is not found in the map
  9. if(m.find(num) == m.end()){
  10. m[num] = res.size()-1;
  11. long q = num/den;
  12. long r = num%den;
  13.  
  14. res+= to_string(q);
  15. num = r*10;
  16. } else {
  17. ans = res.substr(0,m[num]+1) + "(" + res.substr(m[num]+1,res.size()-m[num]) + ")";
  18. res = ans;
  19. break;
  20. }
  21.  
  22. }
  23. }
  24. string fractionToDecimal(long numerator, long denominator) {
  25. if(numerator == 0) return "0";
  26.  
  27. string res = "";
  28.  
  29. // negative result
  30. if(numerator < 0 && denominator >0 || numerator > 0 && denominator < 0)
  31. res+="-";
  32. long num = abs(numerator);
  33. long den = abs(denominator);
  34.  
  35. // before the decimal
  36. long q = num/den;
  37. long rem = num%den;
  38.  
  39. res+=to_string(q);
  40.  
  41. // decimal
  42. if(rem == 0)
  43. return res;
  44. res += ".";
  45.  
  46. // after the decimal processing
  47. populateAfterDecimal(rem*10,den,res);
  48. return res;
  49. }