博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Reverse Integer
阅读量:4310 次
发布时间:2019-06-06

本文共 1745 字,大约阅读时间需要 5 分钟。

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.

思路分析:这题比較简单,可是有一个tricky的地方,就是怎样处理溢出的情况。

首先要搞清楚,不管32位机器还是64位机器,java定义int为32位,所以Integer.MAX_VAULE和Integer_MIN_VALUE各自是2^31-1和-2^31,32位把第一位当成符号位。easy得出前面的计算结果(考虑进位的规律或者等比数列求和)。所以这题处理溢出有两个地方要注意,第一对于Integer.MIN_VALUE要单独处理,不要直接取绝对值,否则直接溢出。应该返回0;第二就是要推断是否有

res * 10 + posx % 10 > Integer.MAX_VALUE

可是不能直接这么写,直接这样写从左向右运行code也会溢出,能够换一种写法写成推断是否有

res > (Integer.MAX_VALUE - posx % 10) / 10
假设是直接返回0.最后当x位负数时。返回结果的相反数。

AC Code

public class Solution {    public int reverse(int x) {        //1259        if(x == Integer.MIN_VALUE){            return 0;//Integer.MIN_VALUE is -2^31, the abs of which is larger than Integer.MAX_VALUE(2^31 - 1)        }        int posx = Math.abs(x);        int res = 0;        while(posx != 0){            int rem = posx % 10;            //see whether res * 10 + posx % 10 > Integer.MAX_VALUE if yes, overflow            //note that we move the item except res in the right to the left            if(res > (Integer.MAX_VALUE - rem) / 10){                return 0;            }            res = res * 10 + rem;            posx /= 10;        }        return x>0?

res:-res; } }

转载于:https://www.cnblogs.com/llguanli/p/8915206.html

你可能感兴趣的文章
cookie和session笔记
查看>>
Java中使用注释
查看>>
构建你的第一个App
查看>>
Network Mapper 嗅探工具
查看>>
linux下定时执行任务的方法
查看>>
ASP.NET MVC 常用内置验证特性 简介
查看>>
tuple有无list对key的影响
查看>>
java study3
查看>>
优秀的后台管理界面设计案例分享
查看>>
在VIM中使用GDB调试 – 使用vimgdb
查看>>
数据挖掘中哪些算法使用率较高?
查看>>
编程算法 - 推断二叉树是不是平衡树 代码(C)
查看>>
MySpring dataSource从配置文件获取
查看>>
矩阵的转置
查看>>
如何为SharePoint文档库、文件夹、文件单独设置权限
查看>>
【Linux】linux中很有用的指令(练习)
查看>>
C# 抽象(2)
查看>>
mysql之引擎、Explain、权限详解
查看>>
推荐-zabbix原理篇
查看>>
160809329 仲兆鹏 3
查看>>