LeetCode#7 整数反转(数学)

题目:

 

思路:(题外话:好久不刷题,明显生疏了好多,要捡起来记住当初那一份热爱!)

判断溢出的方法,在将数字反转的同时,专注在int的最大值/10和最小值/10这两个数上进行判断就可以了:

拿正数为例:设res为反转后的数字

if  res > Integer.MAX_VALUE/10 无论res再加上什么数字都会溢出

if res == Integer.MAX_VALUE/10 则res再加上比7大的数字就会溢出

代码:

import java.util.Scanner;

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

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        Solution solution = new Solution();
        int ans = 0,K = 5;
        while(K > 0) {
            K--;
            ans = scan.nextInt();
            System.out.println(solution.reverse(ans));
        }
    }

}

 

 

 

posted @ 2019-11-26 22:07  sykline  阅读(218)  评论(0编辑  收藏  举报