【LeetCode Easy】007 Reverse Integer

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

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

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

查看所有标签

猜你喜欢:

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

The Effective Engineer

The Effective Engineer

Edmond Lau / The Effective Bookshelf, Palo Alto, CA. / 2015-3-19 / USD 39.00

Introducing The Effective Engineer — the only book designed specifically for today's software engineers, based on extensive interviews with engineering leaders at top tech companies, and packed with h......一起来看看 《The Effective Engineer》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码