fork download
  1. #include <cmath>
  2. #include <limits>
  3. #include <iostream>
  4.  
  5. #define MAX_DECIMAL_FRACTION 5
  6. #define DEBUGTRACE(x) // do { std::cerr << x; } while (false)
  7.  
  8. template <typename T, bool is_integer> struct reverse_impl;
  9.  
  10. template <typename T>
  11. struct reverse_impl<T, true>
  12. {
  13. static T reverse(T input)
  14. {
  15. T output;
  16.  
  17. for (output = 0; input; input/=10)
  18. output = (output * 10) + input % 10;
  19.  
  20. return output;
  21. }
  22. };
  23.  
  24. template <typename T>
  25. struct reverse_impl<T, false>
  26. {
  27. static T reverse(T input)
  28. {
  29. if (std::abs(input) <= std::numeric_limits<T>::epsilon())
  30. return T(0);
  31.  
  32. // scale input
  33. int log10 = (int) (std::log(input)/std::log(T(10)));
  34. input *= std::pow(10, MAX_DECIMAL_FRACTION);
  35. input = std::floor(input);
  36. input /= std::pow(10, log10+MAX_DECIMAL_FRACTION);
  37.  
  38. DEBUGTRACE("debug: scaled " << input << " digits: ");
  39.  
  40. int iteration = std::max(log10+MAX_DECIMAL_FRACTION, MAX_DECIMAL_FRACTION);
  41.  
  42. if (std::floor(input) < 1)
  43. {
  44. input *= 10;
  45. iteration--;
  46. }
  47.  
  48. T output;
  49. for (output = T(0);
  50. iteration-- && std::floor(input) >= 1;
  51. input-=std::floor(input), input*=T(10))
  52. {
  53. output = (output / T(10)) + std::floor(input);
  54. DEBUGTRACE(std::floor(input));
  55. }
  56.  
  57. DEBUGTRACE(std::endl);
  58. return output * std::pow(10, log10);
  59. }
  60. };
  61.  
  62. template <typename T>
  63. T reverse(T input)
  64. {
  65. return reverse_impl<T, std::numeric_limits<T>::is_integer>::reverse(input);
  66. }
  67.  
  68. int main()
  69. {
  70. std::cout << reverse(-123l) << std::endl;
  71. std::cout << reverse(123ul) << std::endl;
  72.  
  73. std::cout << reverse(123456.0) << std::endl;
  74. std::cout << reverse(0.027f) << std::endl;
  75.  
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 2728KB
stdin
Standard input is empty
stdout
-321
321
654321
0.72