Below is an easy function to reserve a signed integer in C++

#include <iostream>

#include <string>

int reverse(int x) {
  int rev = 0;
  int max = 2147483647;
  int min = -2147483648;

  while (x != 0) {
    int pop = x % 10;
    x /= 10;
    if (rev > max / 10 || (rev == max / 10)) return 0;
    if (rev < min / 10 || (rev == min / 10)) return 0;
    rev = rev * 10 + pop;
  }
  return rev;
}

int main() {
  std::cout << reverse(-1234);
}

 

Output:

 

Last modified: May 31, 2020

Author

Comments

Write a Reply or Comment

Your email address will not be published.