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
主要需要考虑数值越界的问题。在传入参数时判断是否越界,对计算结果用long类型存放,防止计算过程中越界。
代码:
class Solution {
public int reverse(int x) {
long res = 0;
if(x>Integer.MAX_VALUE||x<Integer.MIN_VALUE)
return (int)res;
while(x!=0) {
int m = x%10;
x = x/10;
res = res*10+m;
}
if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE) {
res = 0;
}
return (int)res;
}
}