反向整数leetcode-如何处理溢出 [英] Reverse Integer leetcode -- how to handle overflow

查看:152
本文介绍了反向整数leetcode-如何处理溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是:
整数的倒数。

The problem is: Reverse digits of an integer.

示例1:x = 123,返回321

Example1: x = 123, return 321

Example2:x = -123,返回-321

Example2: x = -123, return -321

您是否注意到反向整数可能溢出?假设输入是一个32位整数,则1000000003的反向溢出。

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?

抛出异常?很好,但是如果无法抛出异常怎么办?然后,您将不得不重新设计该功能(即,添加一个额外的参数)。

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

我搜索的网站的解决方案是:

The solution from the website I search is:

public class Solution {

     public static int reverse(int x) {
            int ret = 0;
            boolean zero = false;
            while (!zero) {
                ret = ret * 10 + (x % 10);
                x /= 10;      
                if(x == 0){
                    zero = true;
                }
            }
            return ret;   
        }

    public static void main(String[] args) {
        int s = 1000000003;
        System.out.println(reverse(s));
    }

}

但是,当 s = 1000000003 ,控制台将显示 -1294967295 而不是 3000000001 。因此,如果我们不能使用异常,此解决方案仍然不能解决溢出问题。这里有什么帮助?(尽管有提示:添加一个额外的参数,但我仍然无法弄清楚应该添加哪个参数)

However when s = 1000000003, the console prints -1294967295 instead of 3000000001. So this solution still does not solve the overflow problem if we cannot use exception. Any help here?(Although there is a hint: add an extra parameter, I still cannot figure out what parameter I should add)

推荐答案

除了int外,不需要任何其他数据类型。
只需确保在进行某操作时会增加一个数字,将其取反即可为您提供上一个数字。

There's no need for any data type other than int. Just make sure when there's an operation that increases a number, reversing the operation should give you the previous number. Otherwise, there's overflow.

public int reverse(int x) {
    int y = 0;

    while(x != 0) {
        int yy = y*10 + x%10;

        if ((yy - x%10)/10 != y) return 0;
        else y = yy;

        x = x/10;   
    }
    return y;
}

这篇关于反向整数leetcode-如何处理溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆