题目:
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的除法:负数的 // 是向下取整(-1 // 10 == -1,-1 % 10 == 9),所以要先取绝对值,最后再把符号乘回去
代码:
class Solution:
def reverse(self, x: int) -> int:
result = 0
sign = -1 if x < 0 else 1
x = abs(x)
while(x):
result = result * 10 + x % 10
x //= 10
print("x:", x)
print("result:", result)
result *= sign
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;
}
};
“`
请我喝杯咖啡
