【LeetCode Easy】007 Reverse Integer

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

内容简介: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类型

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

查看所有标签

猜你喜欢:

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

PHP、MySQL和Apache编程导学

PHP、MySQL和Apache编程导学

梅隆尼 / 李军 / 2009-1 / 59.00元

《PHP、MySQL和Apache编程导学(原书第4版)》介绍Web应用开发的强大组合工具:MySQL、Apache和PHP,共分为六个部分。第一部分引领读者深入了解、安装和配置MySQL、Apache和PHP。第二部分讲解PHP语言基础,包括数组和对象这样的结构化元素。第三部分介绍中级应用程序开发的主题,包括使用表单和文件、限制访问以及完成包含某个专门概念的小项目。第四部分介绍使用数据库的一般性......一起来看看 《PHP、MySQL和Apache编程导学》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器