前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >7. Reverse Integer(注意越界问题)

7. Reverse Integer(注意越界问题)

作者头像
yesr
发布2019-03-14 13:02:18
1K0
发布2019-03-14 13:02:18
举报
文章被收录于专栏:leetcode_solutionsleetcode_solutions

Reverse Integer

【题目】

Given a 32-bit signed integer, reverse digits of an integer.

(翻译:给定一个 32 位有符号整数,将整数中的数字进行反转。)

Example:

代码语言:javascript
复制
Input: 123
Output: 321

Input: -123
Output: -321

Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

(假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31,  2^31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。)

【分析】

这是非常简单的一道题,唯一需要注意的就是越界问题。

int类型的范围是:-2 ^31 ~ 2 ^31 - 1(-2147483648~2147483647),假设我们输入的整数是1234567899,reverse后就变成了9987654321,超出int最大范围,也就会出现越界错误。所以为了避免这种情况,我们在定义最终返回结果的时候,应该使用long型而不是int型。

另外,还需要掌握的方法就是通过不断的取余来获取个位数字,通过/ 10运算来获取个位前面的数字。

Java实现代码如下:

代码语言:javascript
复制
class Solution {
    public int reverse(int x) {
        long res = 0;
        while (x != 0) {
            res = res * 10 + x % 10;
            x /= 10;
            if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
        }
        return (int)res;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月07日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reverse Integer
  • 【题目】
  • 【分析】
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档