Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. ///////////////////////////////
  2. // my solution
  3. ///////////////////////////////
  4. int reverse(int x) {
  5.  
  6. if (x == 0) return x;
  7.  
  8. int xx = x;
  9. bool minus = false;
  10. if (xx < 0)
  11. {
  12. if (xx==numeric_limits<int>::min()) return 0;
  13. minus = true;
  14. xx = -1 * xx;
  15. }
  16.  
  17. long long y = 0;
  18. while (xx) {
  19. int d = xx%10;
  20. y = y*10 + d;
  21. xx = xx/10;
  22. }
  23.  
  24. if (y < numeric_limits<int>::min()) return 0;
  25. if (y > numeric_limits<int>::max()) return 0;
  26.  
  27. return minus ? -y : y;
  28. }
  29.  
  30.  
  31.  
  32. ///////////////////////////////
  33. // improved
  34. //////////////////////////////
  35. int reverse(int x) {
  36.  
  37. using LL = long long int;
  38.  
  39. LL num = x;
  40. LL ans = 0;
  41.  
  42. while (num)
  43. {
  44. ans = (ans*10) + (num%10);
  45. num = num/10;
  46. if (ans > numeric_limits<int>::max() ||
  47. ans < numeric_limits<int>::min() )
  48. return 0;
  49. }
  50.  
  51. return static_cast<int>(ans);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement