7. Reverse Integer

题目:

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.

 

Hide Tags
  Math  

链接: http://leetcode.com/problems/reverse-integer/

题解:

reverse一个整数,主要考察乘10时的overflow的问题。可以设置一个条件,当临时结果大于Integer.MAX_VALUE / 10或者临时结果小于Integer.MIN_VALUE / 10的时候,后面运算乘10肯定会溢出,所以直接return 0给出结果。

不需要处理当临时结果等于Integer.MAX_VALUE或者Integer.MIN_VALUE时的情况, 因为Integer.MAX_VALUE = 214783647,Integer.MIN_VALUE = -214783648。除以10为 21478364或者 - 21478364,假如输入是有效的Integer,最后一位必为1,否则输入不在32位int的范围里。所以此时 x % 10 = 1,临时结果result乘10再加1后不会造成最终结果溢出。

Time Complexity - O(logx), Space Complexity - O(1)。

public class Solution {

    public int reverse(int x) {

        if(x == 0)

            return 0;

        int result = 0;
while(x != 0){ if(result > Integer.MAX_VALUE / 10 || result < Integer.MIN_VALUE / 10) return 0; result = result * 10 + x % 10; x /= 10; } return result; } }

 

测试:

你可能感兴趣的:(Integer)