前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 7. Reverse Integer(反转整数)

LeetCode 7. Reverse Integer(反转整数)

作者头像
明明如月学长
发布2021-08-27 16:13:34
2420
发布2021-08-27 16:13:34
举报

题目网址:https://leetcode.com/problems/reverse-integer/description/

题目要求:

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

Example 1:

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

Example 2:

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

Example 3:

代码语言:javascript
复制
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.

算法思路:

  • 定义一个整数变量result = 0
  • 通过取余,每次获取一个个位数(tail)
  • tail*10+result 即为反转后的数字
  • 为了防止反转后的数字越界要判断反转后的数字/10 是否和原数相等

代码:

代码语言:javascript
复制
    /**
     * 反转整数
     * @param x 整数
     * @return 反转
     */
    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;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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