LEETCODE 7. Reverse Integer 判断溢出的解决方案

来源:互联网 发布:网络大专可以做人事吗 编辑:程序博客网 时间:2024/06/07 03:19

题目:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.



要求能判断溢出,若溢出则返回0。

网上的大部分解法是用更长的long型来判断是否超过了int的32位来判断溢出。网上的第二种解法是用String类型来判断,本质还是用了更长的数据类型。


但是这样质保不治本,因为如果题目要求翻转一个64位的long型变量,则没有更大的数据类型(或者永远都可以要求翻转最大的数据类型)。


我的方法是在最后一次“乘以10然后加余数”之前,判断这个值是否接下来会溢出,核心代码如下:


public int reverse(int n) {int initiall = n;int result = 0;int count = 0;for (int ii = 0; initiall != 0; count++) {initiall = initiall / 10;}for (int i = 0; i < count; i++) {if (i == count - 1) {if (result > Integer.MAX_VALUE / 10|| ((result == Integer.MAX_VALUE / 10) && (n % 10 > Integer.MAX_VALUE % 10))) {result = 0;break;}if (result < Integer.MIN_VALUE / 10|| ((result == Integer.MIN_VALUE / 10) && (n % 10 < Integer.MIN_VALUE % 10))) {result = 0;break;}}result = result * 10 + n % 10;n = n / 10;}return result;}


1 0