【LeetCode Easy】007 Reverse Integer

11次阅读

共计 730 个字符,预计需要花费 2 分钟才能阅读完成。

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 类型
正文完
 0