水题。但题下的注释还是有点启发的,一个是比如120反转,一个是反转后有可能int溢出。前者不需要特殊处理,后者需要clarify,如果发生是否以另一个参数传出或抛出异常。
public class Solution {
public int reverse(int x) {
// Start typing your Java solution below
// DO NOT write main() function
int result = 0;
boolean neg = false;
if (x < 0)
{
neg = true;
x = -x;
}
while (x != 0)
{
int r = x - x / 10 * 10;
x = x / 10;
result = result * 10 + r;
}
if (neg)
{
result = - result;
}
return result;
}
}