首页 > 代码库 > LeetCode 007 Reverse Integer - Java

LeetCode 007 Reverse Integer - Java

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

 

定位:简单题

将输入的数反转输出,注意的是负数符号保持在最前,反转后的值超出int_32bit范围输出0。

简单的将传如的数分离符号后用StringBuffer进行反转,然后转化为int,此时尝试抓取NumberFormatException的错误,如有直接为0。

 

Java实现:

 1 public class Solution {
 2     public int reverse(int x) {
 3         boolean isNev=false;
 4         if(x<0){
 5             x=-x;
 6             isNev=true;
 7         }
 8         StringBuffer stringBuffer=new StringBuffer(String.valueOf(x));
 9         stringBuffer=stringBuffer.reverse();
10         int y;
11         try{
12             y=Integer.parseInt(stringBuffer.toString());
13         }catch (NumberFormatException e){
14             y=0;
15         }
16         if(isNev){
17             y=-y;
18         }
19         return y;
20     }
21 }

 

LeetCode 007 Reverse Integer - Java