---
# System prepended metadata

title: 7. Reverse Integer
tags: [C++, LeetCode-Easy]

---

# 7. Reverse Integer
Difficulty: Easy

## Solution

```cpp=
/**
*** Author: R-CO
*** E-mail: daniel1820kobe@gmail.com
*** Date: 2020-10-26
**/
#include <cstdint>  // INT32_MAX
#include <cstdlib>  // EXIT_SUCCESS, abs()

class Solution {
 public:
  int reverse(int x) {
    int answer = 0;
    int remainder = 0;
    bool is_positive = (x >= 0);
    x = abs(x);

    while (x > 0) {
      remainder = x % 10;
      static const int kOverflowDetectValueForAnswer = INT32_MAX / 10;
      static const int kOverflowDetectValueForRemainder = INT32_MAX % 10;
      if (answer > kOverflowDetectValueForAnswer ||
          (answer == kOverflowDetectValueForAnswer &&
           remainder > kOverflowDetectValueForRemainder)) {
        return 0;  // overflow
      }

      answer = answer * 10 + remainder;
      x /= 10;
    }

    answer = (is_positive) ? answer : (answer * -1);

    return answer;
  }
};

int main(int argc, char *argv[]) { return EXIT_SUCCESS; }

```

## Result

Success
Details 
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reverse Integer.
Memory Usage: 6.5 MB, less than 5.78% of C++ online submissions for Reverse Integer.


###### tags: `LeetCode-Easy` `C++`
