[LeetCode] 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.

 

注意:OJ更新了溢出测试,所以还是要考虑溢出。

Java:

public class Solution {
    public int reverse(int x) {
        long result = 0;
        int tmp = Math.abs(x);
        while(tmp>0){
            result *= 10;
            result = result * 10 + tmp % 10;
            if(result > Integer.MAX_VALUE){
                return 0;
            }
            tmp /= 10;
        }
        return (int)(x>=0?result:-result);
    }
}

Python:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 0:
            return -self.reverse(-x)

        result = 0
        while x:
            result = result * 10 + x % 10
            x //= 10
        return result if result <= 0x7fffffff else 0  # Handle overflow.

C++:

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (abs(res) > INT_MAX / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

C++:

class Solution {
public:
    int reverse(int x) {
        int result = 0;
        while (x) {
            auto prev = result;
            result *= 10;
            result += x % 10;
            if (result / 10 != prev) {
                result = 0;
                break;
            }
            x /= 10;
        }
        return result;
    }
};

 

类似题目:

[LeetCode] 190. Reverse Bits 翻转二进制位

 

All LeetCode Questions List 题目汇总

  

posted @ 2018-03-01 16:01  轻风舞动  阅读(310)  评论(0编辑  收藏  举报