博文中会简要介绍Leetcode P0007题目分析及解题思路。
“Reverse Integer”是一道比较简单的纯数学问题,主要考察边界条件的判断,如果是边界最值的十分之一,则直接返回0,题干如下:
Given a 32-bit signed integer, reverse digits of an integer.
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.
以下是Java的题解代码实现。
class Solution {
public int reverse(int x) {
// int: [-2^31, 2^31-1]
// if (x <= Integer.MIN_VALUE)
// return 0;
int ret = 0;
while (x != 0) {
int digit = x%10;
ret = (ret > Integer.MAX_VALUE/10 || ret < Integer.MIN_VALUE/10)? 0: 10*ret+digit;
x = x/10;
}
return ret;
}
}
以下是C++的题解代码实现。
class Solution {
public:
int reverse(int x) {
// int: [-2^31, 2^31-1]
// if (x <= INT_MIN)
// return 0;
int ret_rev = 0;
while (x != 0) {
int digit = x%10;
if (ret_rev > INT_MAX/10 || ret_rev < INT_MIN/10)
return 0;
ret_rev = 10*ret_rev+digit;
x = x/10;
}
return ret_rev;
}
};