Leetcode algorithm problem 7. Reverse Integer2

7. Reverse Integer

Subject description:

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.

Solution to a problem:

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

In this problem, the main difficulty is the limited integer values ​​to prevent overflow and flip.

  • For inversion a finite integer, the method is used in the present cycle problem, take the remainder, divided by the method of 10
  • For stack overflow

According to the formula:

use:

if (reversed>Integer.MAX_VALUE || (reversed==Integer.MAX_VALUE && pop>7)

if(reversed<Integer.MIN_VALUE || (reversed==Integer.MIN_VALUE && pop<-8))

Solutions to two:

Of course, there is a model solution is to use an array of long, reconverted (int), complex formula is omitted here determined; int type because, if not determined according to the formula, it would overflow, the disadvantage is due to the test data does not exceed the length of the long models, so it can.

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

Guess you like

Origin www.cnblogs.com/zhichun/p/12041151.html