fueanta

Revrese Integer with overflow condition.

May 31st, 2017
134
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class Solution {
  7. public:
  8.     int reverse(int x) {
  9.         long long rev = 0;
  10.         while (x)
  11.         {
  12.             rev *= 10;
  13.             rev += (x % 10);
  14.             x /= 10;
  15.         }
  16.         return ((rev > INT_MAX || rev < INT_MIN) ? 0 : rev);
  17.     }
  18. };
  19.  
  20. int main(void)
  21. {
  22.     cout << "Number to reverse: ";
  23.     int num; cin >> num;
  24.     Solution s;
  25.     int count = 0, original = num;
  26.     while (num % 10 == 0) {
  27.         ++count;
  28.         num /= 10;
  29.     }
  30.     int reverseNum = s.reverse(num);
  31.  
  32.     cout << "\nReversed Number: ";
  33.  
  34.     if (reverseNum < 0) {
  35.         cout << "-";
  36.         reverseNum *= (-1);
  37.     }
  38.     for (int i = 0; i < count; i++)
  39.     {
  40.         cout << "0";
  41.     }
  42.     cout << reverseNum << "\n\n";
  43.     return 0;
  44. }
RAW Paste Data