Leetcode:7. Reverse Integer

题目:
Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range:[-2^31, 2^31 -1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

分析:
注意python的除法

代码:

class Solution:
    def reverse(self, x: int) -> int:
        result = 0
        while(x):
            result = result * 10 + x % 10 
            x //= 10
            print("x:", x)
            print("result:", result)
        if result < -2147483647 or result > 2147483647:
            result = 0

        return result

由于用python执行达到了52ms,所以换成了C++

“`C++

class Solution {
public:
int reverse(int x) {
long result = 0;
while(x){
result = result * 10 + x % 10;
x /= 10;
}
if (result < -2147483647 || result > 2147483647)
result = 0;
return result;
}
};

“`

Author Rewards

Leave a Reply

Your email address will not be published. Required fields are marked *