LeetCode - Reverse Integer

1 minute read

Problem description

description

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

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
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.

Analysis

Basic idea is to store every digit of input integer, and multiple 10 one by one from reverse order.

The main point of this problem is to deal with the edge cases.

edge case 1: Integer.MAX_VALUE and Integer.MIN_VALUE

edge case 2: size of 10(the len of Integer.MAX_VALUE = 2147483647) and will make overflow error, like 1534236469

Here’s code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class ReverseInteger {
  public int reverse(int x) {
    // add this for Math.abs()
    if (x == Integer.MAX_VALUE || x == Integer.MIN_VALUE){
      return 0;
    }

    int factor = x < 0 ? -1 : 1;
    ArrayList<Integer> digits = new ArrayList<>();
    x = Math.abs(x);
    while (x != 0) {
      digits.add(x % 10);
      x = x / 10;
    }

    int res = 0;

    int index = 0;

    while (index != digits.size()){
      int pre = res;
      res = res * 10 + digits.get(index);
      index++;
      // edge case 2
      if ((index == 10 && pre > Integer.MAX_VALUE / 10)){
        return 0;
      }
    }

    if (res != Integer.MIN_VALUE){
      return res * factor;
    }
    else {
      return 0;
    }
  }
}

What to improve

  • use pre > Integer.MAX_VALUE / 10 but not res < pre to check if overflow