前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode]Reverse Integer题解 [LeetCode]Reverse Integer题解

[LeetCode]Reverse Integer题解 [LeetCode]Reverse Integer题解

作者头像
尾尾部落
发布2018-09-04 13:11:27
5960
发布2018-09-04 13:11:27
举报
文章被收录于专栏:尾尾部落尾尾部落

题目链接:7. Reverse Integer 难度:Easy

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

要点 本题考查的是整数相加的溢出处理,检查溢出有这么几种办法: – 两个正数数相加得到负数,或者两个负数相加得到正数,但某些编译器溢出或优化的方式不一样 – 对于正数,如果最大整数减去一个数小于另一个数,或者对于负数,最小整数减去一个数大于另一个数,则溢出。这是用减法来避免加法的溢出。 – 使用long来保存可能溢出的结果,再与最大/最小整数相比较 Java

代码语言:javascript
复制
class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (Math.abs(res) > Integer.MAX_VALUE / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

参考:[Leetcode] Reverse Integer 反转整数

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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