Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
Solution 1: Positive/Negative formula is same. Need the positive flag just to deal with the overflow.
public class Solution {
public int reverse(int x) {
boolean positive=true;
if (x<0) positive=false;
int res=0;
while (x!=0) {
int num=x%10;
//to make sure result will not overflow, when overflow return 0
if (positive && res>(Integer.MAX_VALUE-num)/10) return 0;
if (!positive && res<(Integer.MIN_VALUE-num)/10) return 0;
res=res*10+num;
x/=10;
}
return res;
}
}
Solution 2: if can use long in the code, will be much cleaner.
public class Solution {
public int reverse(int x) {
long res=0;
while (x!=0) {
res=res*10+x%10;
if (res>Integer.MAX_VALUE || res<Integer.MIN_VALUE) return 0;
x/=10;
}
return (int)res;
}
}
没有评论:
发表评论