资讯专栏INFORMATION COLUMN

Leetcode 7 Reverse Integer 倒序整数

LoftySoul / 1231人阅读

摘要:原题目为难度此题让我们输出给定一个整数的倒序数比如倒序为倒序为但是如果倒序的过程中发生整型溢出我们就输出倒序不复杂关键在于如何判定将要溢出最终的程序如下其中是获取的个位数字判定下一步是否将要溢出使用

原题目为:

Reverse digits of an integer.
Example1: x = 123, return 321

Example2: x = -123, return -321

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.

难度: Easy

此题让我们输出给定一个整数的倒序数, 比如123倒序为321, -123倒序为-321. 但是如果倒序的过程中发生整型溢出, 我们就输出0.

倒序不复杂, 关键在于如何判定将要溢出.

最终AC的程序如下:

public class Solution {

    public int reverse(int x) {
        int x1 = Math.abs(x);
        int rev = 0;
        while (x1 > 0) {
            if (rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10) {
                return 0;
            }
            rev = rev * 10 + (x1 - (x1 / 10) * 10);
            x1 = x1 / 10;
        }
        if (x > 0) {
            return rev;
        } else {
            return -rev;
        }
    }
}

其中 x1 - (x1 / 10) * 10 是获取x1的个位数字, 判定下一步是否将要溢出, 使用 rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10 .

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66514.html

相关文章

  • [Leetcode] Reverse Integer 反转整数

    摘要:字符串法复杂度时间空间思路先将数字转化为字符串,然后将字符串倒序输出,并转回数字。模十法复杂度时间空间思路通过对数字模十取余得到它的最低位。除了检查溢出返回特定值以外,有没有别的方法处理溢出可以使用代码块排除异常。 Reverse Integer Reverse digits of an integer.Example1: x = 123, return 321Example2: x ...

    ad6623 评论0 收藏0
  • leetcode 7 Reverse Integer

    摘要:题目详情题目要求我们给出一个数的翻转数想法这道题主要的坑就是在于一个数值的输入,在进行翻转操作之后,不一定还符合的范围,可能会造成异常。我们可以通过每次获得整数除的余数,来确定当前整数的最后一位。 题目详情 Given a 32-bit signed integer, reverse digits of an integer.题目要求我们给出一个数的翻转数 Example 1:Inpu...

    microelec 评论0 收藏0
  • LeetCode Easy】007 Reverse Integer

    摘要:第一时间想到这是经典的取模取余运算,但是写的过程中遇到了很多问题这么简单一题基础做法取一个整数的最后一位数字只要把这个整数就可以,要取除最后一位数字之外的其它数字只要是没有长度函数的,需要转化成才能使用长度函数用这个方法最大的难点在 Easy 007 Reverse Integer Description: Given a 32-bit signed integer, reverse ...

    Sourcelink 评论0 收藏0
  • Leetcode7Reverse Integer

    摘要:判断溢出这里使用了中的类整数类,缩写就是的静态变量和,就能直接得到整型变量可表示数值的上下限。当结果不在此范围内时,则溢出,并返回否则返回正常结果。 要点 这一题的要点有三个: 接收长度不同的数字并翻转 判断结果是否溢出 解决方法 翻转:为了能够接收不同长度的数字进行反转操作,我们使用循环结构进行操作。(注:这里创建的sum变量一定要用long类型而不能用int,原因是采用int...

    liaoyg8023 评论0 收藏0
  • LeetCode - 007 - 整数反转(reverse-integer

    摘要:详细介绍将其他值转成数字值。此方法更改数组的长度。详细介绍解题思路首先,将传入的数字转换成字符串,并分割成数组。本许可协议授权之外的使用权限可以从处获得。 Create by jsliang on 2019-05-19 09:42:39 Recently revised in 2019-05-19 16:08:24 Hello 小伙伴们,如果觉得本文还不错,记得给个 star , 小伙伴们...

    venmos 评论0 收藏0

发表评论

0条评论

LoftySoul

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<