LeetCode7 integer inversion-(Java) two methods

Given a 32-bit signed integer, you need to invert the digits on each of the integers.
Example 1: Input: 123 Output: 321
Example 2: Input: -123 Output: -321
Example 3: Input: 120 Output: 21
Note: Assuming that our environment can only store the next 32-bit signed integer, its value The range is [−2^31 ^ ,2 31 −1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

  • Mainly to solve the overflow problem, this is where I was not thoughtful: There are two ideas to solve the overflow problem:
  • The first idea is to solve it by string conversion plus try~catch;
  • The second idea is to solve it through mathematical calculations.

The first method (the idea that I did for the first time):
(1) Consider the case of 0: If x=0, return 0 directly
(2) If x>0, then the boolean variable flag=true; x<0, then flag is false;
(3) For more convenience, after recording the flag, take the absolute value of x;
(4) Split the numbers and add them to the dynamic array in turn;
(5) Considering the inversion, if there is one or more in front If one is 0, you need to go to 0;
(6) After there is no 0 in the front, continue to take out the numbers in the array, in the form of String, and then convert to int.
(7) Catch the exception: return 0 after the inversion of the integer overflow;
(8) Finally, judge the flag and decide whether the returned d is positive or negative.

public int reverse(int x) {
    
    
	// 判断正负
	if (x == 0) {
    
    
		return 0;
	}
	boolean flag = false;
	if (x > 0) {
    
    
		flag = true;
	}
	x = Math.abs(x);
	int d = 0;// 返回
	// 判断几位数,加入数组
	ArrayList<Integer> list = new ArrayList<>();
	while (x != 0) {
    
    
		int a = x % 10;
		list.add(a);
		x /= 10;
	}
	String string = new String();
	int count = 0;
	OUT: for (int i = 0; i < list.size(); i++) {
    
    
		if (list.get(i) == 0) {
    
    
			count++;
			continue;
		}
		for (int j = count; j < list.size(); j++) {
    
    
			string += list.get(j);
		}
		break OUT;
	}
	try {
    
    
		if (Integer.parseInt(string) > Integer.MAX_VALUE) {
    
    
			return 0;
		} else {
    
    
			d = Integer.parseInt(string);
		}
	} catch (Exception e) {
    
    
		return 0;
	}
	if (!flag) {
    
    
		d = -d;
	}
	return d;
}

The second method:
split each bit of the number x through a loop, and judge whether it overflows at each step when calculating the new value

class Solution {
    
    
   public int reverse(int x) {
    
    
      long temp = 0;
      while(x != 0){
    
    
          int pop = x % 10;
          temp = temp * 10 + pop;
          if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE){
    
    
              return 0;
          }
          x /= 10;
      }
      return (int)temp;
  }
}

end.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/108485070