标签:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
We need to consider a lot of cases of input. One particular example is how to deal with many zeros in the end of that number.
The most direct way is use string or char array to store the int number and then convert it. But I prefer to use the pure math way to do it as cleaner and easier.
1 public class Solution { 2 public int reverse(int x) { 3 if (x>=0 && x < 10) 4 return x; 5 6 boolean flag = true; 7 8 if (x < 0){ 9 x = 0-x; 10 flag = false; 11 } 12 13 double result = 0; 14 15 while (x > 0){ 16 int mod = x % 10; 17 result = result * 10 + mod; 18 x = x / 10; 19 } 20 21 if (flag) 22 return result > Integer.MAX_VALUE ? 0 : (int)result; 23 else 24 return 0-result < Integer.MIN_VALUE ? 0 : (int)(0-result); 25 26 } 27 }
标签:
原文地址:http://www.cnblogs.com/timoBlog/p/4657921.html