码疯窝

LeetCode 每日一题 — Reverse Integer

2014/12/17 11:30:09    分类: 日志连载    0人评论 次浏览

Reverse digits of an integer.

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

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.

算法分析: 每次取出余数然后拼接起来就可以了. 但是要注意两点, 最后个位为0时怎么办, 还有走出INT 取值范围怎么办?
第一个问题, 如果取余数拼接就不存在这种问题了, 第二个问题超出取值范围的处理, 这一点在不同语言之间是有些许差异的.
C++: 我之前的文章就讲过, 这在里long 型和int 型都是4位的, 故而无法判断int 最大最小值, 所以我用了double型.
Python: Python 是弱类型语言, 不用考虑, 但是要考虑的是 Python 在做负数除法和取模的时候与c++, java是不同的. 如-1 / 5 在 java 中为0, 在Python 中为 -1. 所以 Python 中需要先取绝对值然后再处理.

Java:

public class Solution {
    public int reverse(int x) {
        long rst = 0;
        
        while(x != 0) {
            rst = rst * 10 + x % 10;
            if (rst > Integer.MAX_VALUE || rst < Integer.MIN_VALUE) {
                rst = 0;
                break;
            }
            x /= 10;
        }
        return (int)rst;
    }
}

C++:

class Solution {
public:
    int reverse(int x) {
        double rst = 0;
        while (x != 0) {
            rst = rst * 10 + x % 10;
            if (rst > INT_MAX or rst < INT_MIN) {
                rst = 0;
                break;
            }
            x /= 10;
        }
        return rst;
    }
};

Python:

class Solution:
    # @return an integer
    def reverse(self, x):
        rst = 0
        positive = (x >= 0)
        x = x if positive else -x
        
        while (x != 0 ):
            rst = rst * 10 + x % 10
            if (rst > 2147483647 + (0 if positive else 1)):
                rst = 0
                break
            x /= 10
            
        return rst if positive else -rst
继续查看有关 日志连载的文章

0个访客评论