LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  int reverse(int x) {
    long res = 0;
    while (x) {
      res = res * 10 + x % 10;
      x /= 10;
    }
    if (res > INT_MAX || res < INT_MIN) {
      return 0;
    }
    return res;
  }
};
class Solution {
 public:
  int reverse(int x) {
    int res = 0;
    while (x) {
      int t = x % 10;
      if (res > INT_MAX / 10 || (res == INT_MAX / 10 && t > (INT_MAX % 10))) {
        return 0;
      }
      if (res < INT_MIN / 10 || (res == INT_MIN / 10 && t < (INT_MIN % 10))) {
        return 0;
      }
      res = res * 10 + t;
      x /= 10;
    }
    return res;
  }
};