1. 程式人生 > >Python實現“反轉整數”的兩種方法

Python實現“反轉整數”的兩種方法

給定一個32位的符號整數,返回它的反轉整數

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21

假設該整數的大小範圍為:[-2^{31}, 2^{31}-1],如果反轉整數溢位,就返回0。

1:正常整數方法實現,利用餘數*10累加的方法完成。需要注意的是,python對整數除法採用“向下取整”機制,所以正數和負數要區別運算。

def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        num = 0
        if x == 0:
            return 0
        if x < 0:
            x = -x
            while x != 0:
                num = num*10 + x%10
                x = x/10
            num = -num
        else:
            while x != 0:
                num = num*10 + x%10
                x = x/10
            
        if num>pow(2,31)-1 or num < pow(-2,31):
            return 0
        return num

2:整數轉字串,反轉字串,然後再轉整數

def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        plus_minus = ""
        reverse_x = ""
        if x<0:
            plus_minus = "-"
            x = -x
        for i in str(x):
            reverse_x = i + reverse_x
        reverse_x = plus_minus +reverse_x
        if int(reverse_x)>pow(2,31)-1 or int(reverse_x)<pow(-2,31):
            return 0
        return int(reverse_x)