7. Reverse Integer

https://leetcode.com/problems/reverse-integer/description/
Topic: Given an integer, return the integer in reverse order of each bit.
Problem-solving idea: initial old = 0, take the lowest bit tail of integer n each time, and then construct a new integer new = old * 10 + tail from low to high. After obtaining the tail, remove the lowest bit of n, n=n/10, and enter the next round until n=0.
Note that in order to avoid overflow, record old and new each time, and then use the opposite method: old = (new-tail)/10, to determine whether old and new are equal, if they are not equal before and after, it indicates overflow.

Code:

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

Python implementation: basically the same as the c language, the difference is that the modulo and division of negative numbers require special processing, which is simplified here to be processed with positive numbers first, and then converted to negative numbers. In addition, it is necessary to pay attention to judging whether there is overflow, because the integer type range of python seems to be larger than that of c language, so it is not necessary to judge the overflow by the above method, just check whether it is there or not [-2^31, 2^31-1].

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        result = 0
        while x != 0:
            if x > 0:  
                tail = x % 10
            else:
                tail = -(-x % 10)   #考虑负数处理         
            newResult = result * 10 + tail          
            if x > 0:
                x //= 10
            else:
                x = -(-x // 10)  #考虑负数处理
            result = newResult

        if result < 2**31-1 and result > -2**31:
            return result
        else:
            return 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325698425&siteId=291194637