Weikoi

导航

Leetcode-007-整数反转

本题为基础题,注意两个点即可,其一为整数的上下限如何表示,其二是注意 Java 和 Python 的负数整除机制是不同的,Java -3/2 是 -1,而 Python  -3 // 2 是 -2.

class Solution {
    public int reverse(int x) {
        
        long result = 0;
        while(x!=0){
            result = result*10 + x%10;
            x/=10;
        }
        if(result > Integer.MAX_VALUE || result<Integer.MIN_VALUE){
            return 0;
        }
        return (int)result;
    }
}
class Solution:
    def reverse(self, x: int) -> int:
        if(x<0):
            isPos = -1
            x = x*isPos
        else:
            isPos = 1
        result = 0
        while x!=0:
            result = result * 10 + x % 10
            x//=10
        if result>2**31-1 or -result<-2**31:
            return 0
        return isPos*result

 

posted on 2020-02-22 15:53  Weikoi  阅读(175)  评论(0)    收藏  举报