leetcode整数反转第七题

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。https://leetcode-cn.com/problems/reverse-integer/
整数反转比较简单 每次对10进行取余得到最末尾的数 然后更新要反转数的值
主要就是要注意溢出的问题 所以需要对计算结果进行溢出的判断 当大于Max_Value和小于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);
}
}

猜你喜欢

转载自www.cnblogs.com/phantom576/p/11648878.html