leetcode_java_第二题 ReserveInteger

来源:互联网 发布:java rmi exp 编辑:程序博客网 时间:2024/06/07 03:48

  题目:

 

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

  就是把一个整型的数进行反转,思路其实很简单就是网上说的“模十法”。但是我刚开始想的时候就很复杂,我想着创造一个数组来存储改数字用10取模的每一位然后在以此计算。这个过程出现的麻烦是第一要计算这个数字的长度,第二个是要在反向的时候控制乘以的第一位的大小。这个就很麻烦。而且我还没有考虑到溢出的问题,也没有考虑到如果最后一位是零的情况。所以整体来说,这道题我的代码真的很失败,用了很多的for,但是最后还是超时了。

 /* 在贴出答案的同时,OJ还提了一个问题 To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why? (214748364 即为 INT_MAX /10

为什么不用check是否等于214748364呢,因为输入的x也是一个整型数,所以x的范围也应该在 -2147483648~2147483647 之间,那么x的第一位只能是1或者2,翻转之后res的最后一位只能是1或2,所以res只能是 2147483641 或 2147483642 都在int的范围内。但是它们对应的x为 1463847412 和 2463847412,后者超出了数值范围。所以当过程中res等于 214748364 时, 输入的x只能为 1463847412, 翻转后的结果为 2147483641,都在正确的范围内,所以不用check。*/(引用,适用于c++,但是我获益匪浅)

 

class Solution {    public int reverse(int x) {        int res = 0;        int t;        while ( x != 0 ) {            t = res*10 + x%10;            if(t/10 != res ) return 0;            res = t;            x = x/10;        }        return res;    }}
  这个代码的模十法首先就很让我学习,当循环结束的时候,res就已经完成的反转。仔细想想,因为取模每一次取的都是最后一位,所以每一次的结果乘以10就是已经把位数给考虑在内了,所以就不用再去想位数的问题了。而设置的变量t是为了检查溢出,原因就是如果溢出的话,那么计算的t消去最后一位肯定和原来的返回值是不相同的,因此也满足了检查溢出的功能。

  才开始写leetcode有点不适应,但是一定要坚持下去啊!!


原创粉丝点击