码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#7 整数反转(数学)

时间:2019-11-26 23:02:53      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:height   eth   ann   最大值   out   判断   method   --   专注   

题目:

技术图片

 

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

判断溢出的方法,在将数字反转的同时,专注在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));
        }
    }

}

 

 

 

LeetCode#7 整数反转(数学)

标签:height   eth   ann   最大值   out   判断   method   --   专注   

原文地址:https://www.cnblogs.com/sykline/p/11938802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!