If result is overflow, then return -1.
1 public class Solution { 2 public int reverse(int x) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 boolean positive = true; 6 if(x < 0) 7 positive = false; 8 x = Math.abs(x); 9 int result = 0; 10 while(x>0) 11 { 12 result = result * 10 + x % 10; 13 x /= 10; 14 } 15 if(result < 0) 16 return -1; 17 return positive?result:(-1*result); 18 19 } 20 }