7. Reverse Integer

Problem:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solutions:

class Solution {
public:
    int reverse(int x) {
        bool sign = (x >= 0);
        if (x == INT_MIN)   return 0;
        x = abs(x); // it is wrong if x is INT_MIN because of overflow.

        int ret = 0;
        while (x > 0) {
            int digit = x%10;
            x /= 10;
            if (ret > INT_MAX/10 || (ret == INT_MAX/10 && (sign ? digit > INT_MAX%10 : digit > INT_MAX%10 + 1)))    return 0; // the priority of conditional operator is low && abs(INT_MIN) is forbidon!!!
            ret = ret * 10 + digit;
        }

        return sign ? ret : -ret;
    }
};

More concise solution

From https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/

It is not necessary to distinguish whether x is negative or not.

The rule to determine the sign of modulus is explained at one https://stackoverflow.com/questions/7594508/modulo-operator-with-negative-values.
Simple examples are shown below.

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1
// Author: Huahua
class Solution {
public:
  int reverse(int x) {
    int ans = 0;
    while (x != 0) {
      int r = x % 10;
      if (ans > INT_MAX / 10 || ans < INT_MIN / 10) return 0;
      ans = ans * 10 + r;
      x /= 10;
    }
    return ans;
  }
};

results matching ""

    No results matching ""