Another approach to ReverseInteger
daveziegler55 opened this issue · comments
"For ReverseInteger I thought maybe you would like to see a different approach for this problem, this is what I would do:
public int reverse(int x) {
int ne=x<0 ? -1 : 1;
x=Math.abs(x);
long a=x%10;
x/=10;
while (x!=0){
a*=10;
a+=x%10;
if(a < Integer.MIN_VALUE || a > Integer.MAX_VALUE)return 0;
x/=10;
}
return Long.valueOf(a*ne).intValue();
}"
- No need to worry about the sign. The reversing operations singly on x, so sign won't change anyway.
- No need to do the extra mode, and division outside of the loop.
- sum and mod can be done in one line:
rst = rst * 10 + x%10