7.Reverse Integer  

 

 

class Solution:
    def reverse(self, x: int) -> int:
        isNegative = x < 0
        sum = 0
        abs_x = abs(x)
        while abs_x:
            sum = sum * 10
            i = abs_x % 10
            sum = sum + i
            abs_x = abs_x//10
        
        if sum > 2**31-1:
            return 0
        elif isNegative:
            return -sum
        else:
            return sum

 

Java:

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

 

posted @ 2020-05-09 14:11  星海寻梦233  阅读(113)  评论(0编辑  收藏  举报