[LeetCode]7、Reverse Integer

[LeetCode]7、Reverse Integer

题目描述:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路:

  给出一个整数,翻转它。如123 -> 321 -123 ->-321 320 ->23
  判断越界问题,int型的数值范围是 -2147483648~2147483647

 1 public class Solution7 {
 2     public int reverse(int x){
 3         int result = 0;
 4         while(x!=0){
 5             if (Math.abs(result) > Integer.MAX_VALUE / 10) return 0;//越界判断
 6             result = result * 10 + x % 10;
 7             x = x/10;
 8         }
 9         
10         return result;
11     }
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14         int x = 1000000009;
15         Solution7 solution7 = new Solution7();
16         System.out.println(solution7.reverse(x));
17     }
18 
19 }