【LeetCode Easy】007 Reverse Integer

栏目: 编程工具 · 发布时间: 5年前

内容简介:Given a 32-bit signed integer, reverse digits of an integer.Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function ret

Easy 007 Reverse Integer

Description:

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

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

==Example==

123→321 -123→-321 120→21

My Solution:

  1. 第一时间想到这是经典的取模取余运算,但是写的过程中遇到了很多问题QAQ(这么简单一题

    • 基础做法:取一个整数的最后一位数字只要把这个整数 % 10就可以,要取除最后一位数字之外的其它数字只要 / 10
    • int是没有长度函数的,需要转化成String才能使用长度函数
    • 用这个方法最大的难点在于用int类型时处理溢出问题,原本没有溢出的数字在进行翻转时很有可能溢出,最合适的方法是在处理过程中进行 预判

      • 假设翻转过程的中间值用res来保存,每次取下来的那个数字用pop来保存,overflow = 2147483646,underFlow = -2147483647
      • 已知当res * 10 + pop 会引起溢出时,res必定是 ≥ (max / 10)或 ≤ (min / 10)的,其中相等时对pop由要求
      • 根据上述条件在翻转时进行溢出预判

Fast Solution:

  1. 题目中要求的溢出条件其实是针对int型数据的,这题用 Java 来写的话其实可以用long类型

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

思考的乐趣

思考的乐趣

顾森 / 人民邮电出版社 / 2012-6 / 45.00元

本书是一个疯狂数学爱好者的数学笔记,面向所有喜爱数学的读者。从2005年7月开始,作者已经写了连续六年的博客,积累下来了大量的数学文章。 部分文章内容被广泛关注,在网络上大量分享转载。 这本书有意挑选了初等的话题,让大大小小的读者都能没有障碍地阅读。文章内容新,让有数学背景的人也会发现很多自己没见过的初等问题。 文章是独立的。一篇文章一个话题,文章与文章之间基本不会做参考,读者可以随意跳着看......一起来看看 《思考的乐趣》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具