leetcode integer reversal seventh title

Gives a 32-bit signed integer, you need this integer number on each inverted. https://leetcode-cn.com/problems/reverse-integer/
integer relatively simple reversal every 10 to take the remainder to get the most number of end and then update the value to be inverted number of
mainly pay attention to overflow problem is needed determination of when the calculation result is greater than Max_Value overflow and an overflow occurs less than Min_value
package com.lzh.simple;

import java.util.Scanner;

public class ReverseDemo7 {
//数值的反转
public static int reverse(int x){
int ans = 0;
int temp = 0;
while(x!=0){
temp = x%10;
if(ans>Integer.MAX_VALUE/10||(ans==Integer.MAX_VALUE/10&&temp>7)){
return 0;
}
if(ans<Integer.MIN_VALUE/10||(ans==Integer.MIN_VALUE/10&&temp<-8)){
return 0;
}
ans = ans*10+temp;
x = x/10;
}
return ans;
}
//测试
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int res = reverse(x);
System.out.println(res);
}
}

Guess you like

Origin www.cnblogs.com/phantom576/p/11648878.html