Leetcode7. Reverse Integer

来源:互联网 发布:apache 下载 编辑:程序博客网 时间:2024/05/17 06:39

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.

Update (2014-11-10):

Test cases had been added to test the overflow behavior.

这道题,我是用Stack来缓存数据,然后在拼接回去,通过long型来规避Overflow的问题。

public class Solution {    public int reverse(int x) {   Stack<Integer> stack = new Stack<>();      int y =x;      while(y!=0){          stack.push(y%10);          y=y/10;      }      long s = 0;      long t =1;      while (stack.size() !=0){          s+=stack.pop()*t;          t*=10;      }      if(s > Integer.MAX_VALUE || s <Integer.MIN_VALUE){          s = 0;      }      return (int)s;    }}
时间复杂度和空间复杂度均为O(n), 其中n为数字的位数。由于n不可能很多,所以影响不大。

论坛上看到更加精简的解法点击打开链接。

public int reverse(int x){    int result = 0;    while (x != 0)    {        int tail = x % 10;        int newResult = result * 10 + tail;        if ((newResult - tail) / 10 != result)        { return 0; }        result = newResult;        x = x / 10;    }    return result;}


0 0