【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类型

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

查看所有标签

猜你喜欢:

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

计算机算法基础

计算机算法基础

余祥宣、崔国华、邹海明 / 华中科技大学出版社 / 2006-4 / 29.80元

《计算机算法基础》围绕算法设计的基本方法,对计算机领域中许多常用的非数值算法作了精辟的描述,并分析了这些算法所需的时间和空间。《计算机算法基础》可作为高等院校与计算机有关的各专业的教学用书,也可作为从事计算机科学、工程和应用的工作人员的自学教材和参考书。一起来看看 《计算机算法基础》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

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

HEX CMYK 互转工具