你的位置:首页 > Java教程

[Java教程]7. Reverse Integer java


Reverse digits of an integer.

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

 

代码如下:

public class Solution {
    public int reverse(int n) {
        long sum=0;
        int flag=1;
       
        if(n<0)
        {
            flag=-1;
            n=n*(-1);
        }
        try{
        String s=Integer.toString(n);
        s=new StringBuffer(s).reverse().toString();
        sum=Integer.valueOf(s)*flag;
        }catch(NumberFormatException e)
        {return 0;}
 
    return (int)sum;
    }
}