前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 7. Reverse Integer分析代码

LeetCode 7. Reverse Integer分析代码

作者头像
desperate633
发布2018-08-22 15:53:07
2670
发布2018-08-22 15:53:07
举报
文章被收录于专栏:desperate633

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. 将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

分析

通过取余得到最后一位,循环,对于溢出进行判断即可

代码

代码语言:javascript
复制
public int reverse(int x) {
        int result = 0;

        while(x != 0) {
            int tail = x % 10;
            int newResult = result * 10 + tail;
            if((newResult-tail)/10 != result)
                return 0;
            result = newResult;
            x = x/10;
        }
        return result;
    }

image.png

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.06.03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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